Single-chain table reverse Java, single-chain reverse java
Common linked list operations-reverse
Let's first define a node class for a single-chain table.
1 public class ListNode {2 int val; 3 ListNode next = null; // point to the next node 4 5 ListNode (int val) {6 this. val = val; 7} 8}
Two methods are available for single-chain table reversal.
1. Use recursion to reverse from the back to the back. Start from the Start Node, locate it until the end node is found, and then start to reverse.
1 public ListNode reverseList (ListNode head) {2 if (head = null | head. next = null) 3 return head; 4 5 ListNode prev = reverseList (head. next); // recursive call, first reverse the next node 6 7 head. next. next = head; // point the pointer field of the current node to the 8 head of the previous node. next = null; // the pointer field of the previous node makes it null; 9 return prev; // The first node 10 of the new linked list after the reversal}
2. Use traversal to reverse the query. First, save the next node, and then point the current node to the previous node. Then, move the node downward and continue the cycle for the next reversal.
1 public ListNode reverseList (ListNode head) {2 if (head = null) {3 return null; 4} 5 ListNode pre = null; 6 ListNode next = null; 7 while (head! = Null) {8 // save the next node to prevent 9 next = head loss. next; 10 // point his next node to the 11 head of the previous node. next = pre; 12 13 // after the head points to the pre, it will continue to reverse the next node in turn 14 // Let the pre and head move one node backward, continue the next reversal of 15 pre = head; 16 head = next; 17} 18 return pre; 19}
After finishing online programming, you can easily record it and view it later.