The requirements are simple, enter a list, invert the linked list, and output the table header of the new list.
?? Reverse linked list is 2 methods (recursive method, traversal method) implementation, the interviewer's favorite algorithm is nothing more than the Fibonacci sequence and single-linked list inversion, recursive method to achieve a more elegant chain list reversal, but for the students do not understand the recursion is still difficult to understand.
Recursive method
In general, recursion starts with the last node and replaces the pointer order in the process of the stack.
To make it easy to understand, we use the 1->2->3->4 list as a demonstration. The effect of the output is 4->3->2->1
First define node:
publicstaticclass Node { publicint value; public Node next; public Node(int data) { this.value = data; }}
The reversal method is as follows:
publicreverse(Node head) { ifnull || head.nextnull) return head; Node temp = head.next; reverse(head.next); temp.next = head; head.nextnull; return newHead;}
Recursion is essentially a system to help you stack the process, the system in the stack when the site will be retained.
Let's see how it is. A recursive process: 1->2->3->4
Understanding the reversal of a single-linked list (Java implementation)