Singly linked list reversal problem
1. Problem description
Reverse a singly linked list, such as 1-->2-->3-->4-->5-->null
The result after flipping is 5-->4-->3-->2-->1-->null
2. Solution
A traverse the linked list
Split the linked list into an array and then assemble the array into a linked list in reverse order
This method is simple to implement and does not require too many pointers. The disadvantage is that it requires n units of space
B pointer reverse order
Three pointers point to the current node (p), the next node of the current node (q), and the next node of q (r). The existence of r is to modify the next pointer of q to point to p, so that the next value of q will not be lost. The source code is as follows.
public class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
public boolean hasNext() {
return next != null;
}
}
private static Node reverse(Node node) {
Node p = node;
Node q = p.next;
Node r;
p.next = null;
while (q != null) {
r = q.next;
q.next = p;
p = q;
q = r;
}
return p;
}
C recursion
First, treat the part D after the first node as a whole, and think that D is already in reverse order. What we need to do now is to reverse the order of the linked list composed of the first node and D node;
Secondly, it is necessary to reverse the order inside the D node and use the same thinking for processing;
Again, the recursive exit, when the next of the D node is empty, it means that the D node is the last node, just return directly.
The source code is as follows.
/**
*
* @param node 链表头结点
* @param pre 头结点逆序指向的节点
* @return
*/
private static Node reverseRecursion(Node node, Node pre) {
Node head = node;
Node pnext = head.next;
head.next = pre;
if (pnext == null) {
return head;
}
return reverseRecursion(pnext, head);
}
the above