简体   繁体   中英

Reversing a linked-list

I am writing a simple recursive code to reverse a linked-list in Java. Strangely it returns the same node.

Node reverse(Node ptr) {
    if (ptr.link == null)
        return ptr;

    Node second = ptr.link;
    ptr.link = null;

    Node rest = reverse(second);
    rest.link = ptr;

    return rest;
}

Why isn't this working?

Your current approach won't work, the rest value that's being returned from the recursive call doesn't point to the last element in the list (which should be the insertion point for the nodes), instead it's pointing to the first element of the result. In other words, this line isn't correctly building the output:

rest.link = ptr;

For successfully reversing a list, one strategy is to use an accumulator parameter, so we can insert at the head of the list as the recursion unwinds - bear in mind that the recursion starts to "go back" in reverse order with respect to the elements in the list. Try this, it's a tail-recursive solution:

Node reverse(Node ptr, Node acc) {
    if (ptr == null)
        return acc;
    Node second = ptr.link;
    ptr.link = acc;
    return reverse(second, ptr);
}

Call the above method like this:

Node reversedList = reverse(list, null);

Be aware that the input list will be modified in-place and won't be the same after the method returns, any variable that holds a reference to list will be affected. If that's a problem, you should create a copy of list before passing it to reverse() .

Oscar is correct that the return value from recursive call does not point to the last element.

There is another algorithm that does not use accumulator parameter:

function reverse(node) {
  if (node.next == null)
    return node;
  var tail = reverse(node.next);
  node.next.next = node;
  node.next = null;
  return tail;
}
Node reverseNode(Node node){
Node head = null;
While(node.next != null){
    Node n = new Node(node.data);
    n.next = head;
    head = n;
    node = node.next;
}
return head;}

You know you don't have to write a recursive function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM