Issues with reversing objects in a LinkedList

做~自己de王妃 提交于 2019-12-02 05:47:42

I can think of an implementation of appending to standard logic of reversing a list.
If you pass index greater than the number of elements in the list, then it simply reverses the entire list.
If you pass 0 or 1, the list will be unaffected.

public boolean reverseTillIndex(int index) {
    int count = 0;
    if (index == 0) {
        return false;
    }
    Node endCountNode = head;

    while (count++ < index && endCountNode != null) {
        endCountNode = endCountNode.next;
    }
    count = 0;

    // standard reverse a list code
    Node current = head;
    Node h2 = null;

    while (current != null && count++ < index) {
        head = current.next;
        current.next = h2;
        h2 = current;
        current = head;
    }

    head = h2;
    while (h2.next != null) {
        h2 = h2.next;
    }
    h2.next = endCountNode;
    return true;
}

Here is an implementation of reverseSomeMethod() inside your LinkedList class which I believe to be logically correct. It uses recursion to reverse the order of the list. In the base case, it assigns the new head to the current tail, and at each step it links the list in the reverse direction.

public void reverseSomeMethod (Node node) {
    if (node == null || node.next == null) {
        return;
    }
    reverseSomeMethodHelper(node);
    // assign the new tail (the previous head) of the list to point to NULL
    node.next = null;
}

private void reverseSomeMethodHelper(Node node) {
    // base case: assign the new HEAD to old tail, link in reverse, and return
    if (node.next.next == null) {
        setFirst(node.next);
        node.next.next = node;
        return;
    }
    // otherwise traverse deeper in the list
    reverseSomeMethodHelper(node.next);
    // link in reverse order and return
    node.next.next = node;
}

Note that you may have to tweak my code to work with your current implementation. For example, I didn't make much of getters and setters, because your original code did not have them.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!