The following is a detailed analysis of the use of recursive and non-recursive methods to reverse one-way lists of examples, the need for friends can come to reference the next
Problem:
Give a one-way list and turn it upside down. For example: a-> b-> c->d in turn is D-> C-> b-> A.
Analysis:
Suppose the structure of each node is:
Copy Code code as follows:
class Node {
char value;
Node Next;
}
Because the "next" value of each node needs to be updated when the list is reversed, we need to save the next value before updating the next value, otherwise we cannot continue. So, we need two pointers to point to the previous node and the next node, each time after the current node "Next" value is updated, move the two nodes down until the last node is reached.
The code is as follows:
Copy Code code 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 is a recursive method, and this problem can be solved recursively. the code is as follows:
Copy Code code as follows:
Public node reverse (node current)
{
if (current = null | | current.next = NULL) return to current;
Node nextnode = Current.next;
current.next = null;
Node reverserest = reverse (nextnode);
Nextnode.next = current;
return reverserest;
}
The recursive approach is actually very clever, it uses recursion to go to the end of the list, and then update each node next value (code penultimate sentence). In the above code, the value of reverserest does not change to the last node of the list, so, after the inversion, we can get the head of the new list.