How to use recursive and non recursive methods to reverse one way lists

  • 2020-04-02 01:13:48
  • OfStack

Question:
Give a one-way linked list and reverse it from beginning to end. For example: a - > B - > C - > D is just d minus > C - > B - > A.

Analysis:
Suppose that the structure of each node is:


class Node {
 char value;
 Node next;
}

Because we need to update the "next" value of each node when we reverse the list, we need to save the next value before we update the next value, otherwise we cannot continue. Therefore, we need two Pointers to the previous node and the next node respectively, and move the two nodes down each time the current node "next" value is updated, until we reach the last node.

The code is as follows:

public Node reverse(Node current) {
 //initialization
 Node previousNode = null;
 Node nextNode = null;

 while (current != null) {
  //save the next node
  nextNode = current.next;
  //update the value of "next"
  current.next = previousNode;
  //shift the pointers
  previousNode = current;
  current = nextNode;   
 }
 return previousNode;
}

The code above USES a non-recursive approach, which can also be solved recursively. The code is as follows:

public Node reverse(Node current)
 {
     if (current == null || current.next == null) return current;
     Node nextNode = current.next;
     current.next = null;
     Node reverseRest = reverse(nextNode);
     nextNode.next = current;
     return reverseRest;
 }

The recursive method is actually quite clever, it USES recursion to go to the end of the list, and then updates the next value of each node (penultimate sentence of code). In the code above, the value of the reverseRest remains the last node in the list, so if reversed, we can get the head of the new list.


Related articles: