简体   繁体   中英

Reverse Linked-List Recursive

I've traced through my code to reverse a linked-list using recursion, and I cannot find anything wrong with it, but I know it does not work. Can anyone please explain why?

Node reverseLL (Node head) {
  if(curr.next == null) {
    head = curr;
    return head;
  }

  Node curr = head.next;
  prev = head;
  head.next = prev;
  head = next;
  reverseLL(head.next);
}

Below is a working version of your code, added with some helping structures:

class LList {
    Node head;

    void reverse() {
        head = rev(head, head.next);
    }

    private Node rev(Node node, Node next) {
        if(next == null)    return node; //return the node as head, if it hasn't got a next pointer.
        if(node == this.head)   node.next = null; //set the pointer of current head to null.

        Node temp = next.next;
        next.next = node; //reverse the pointer of node and next.
        return rev(next, temp); //reverse pointer of next node and its next.
    }
}

class Node {
    int val;
    Node next;
    public Node(int val, Node next) {
        this.val = val;
        this.next = next;
    }
}

You need to call reverseLL(head.next) before the switching, to traverse down the list and start from the last node upwards. This requires some more changes though.

There are two possible implementation.

First one with a pointer to the head (a class attribute) within your class

class Solution:
head: Optional[ListNode]
    
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
    node = head
    
    if node == None:
        return node
    
    if node.next == None:
        self.head = node
        return
    
    
    self.reverseList(node.next)
    q = node.next
    q.next = node
    node.next = None

    return self.head
    

Second solution, does not rely on a class attribute to conserve the head once you find it. It returns the pointer to the head through the recursive calls stack

def reverseList(head):
  # Empty list is always None
  if not head:
    return None

  # List of length 1 is already reversed
  if not head.next:
    return head


  next = head.next
  head.next = None
  rest = reverseList(next)
  next.next = head

  return rest

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