To implement the reverse of a linked list
Problem Solving Ideas:
To correctly reverse a linked list, you need to adjust the pointer's direction. For example, such as I,m,n is three adjacent nodes, assuming that after a number of steps, the pointer before node I has been adjusted, the next pointer to these nodes point to the previous node. Now traversing to node m, of course, you need to adjust the node's next pointer, let it point to node I, but it should be noted that once the pointer is adjusted to point, the list is broken, because there is no pointer to node n, there is no way to traverse the node n, so in order to avoid the pointer break, You need to save n before adjusting the next m. Next, try to find the head node of the inverted list. It is not difficult to analyze that the head node of the linked list is the end node of the original linked list, that is, next is the node of the null pointer.
The implementation code is as follows:
/** * Two ways to achieve a single-linked list reversal * @author Dream * * / Public class reversesinglelist { /** * Recursion, reverses the next node before reversing the current node * @param node * @return */ Public StaticNodeReverse(Node head) {if(Head = =NULL|| Head.getnextnode () = =NULL){returnHead } Node reversedhead = reverse (Head.getnextnode ()); Head.getnextnode (). Setnextnode (head); Head.setnextnode (NULL);returnReversedhead; }/** * Traversal, changes the current node after the next node of the current node is cached . Public StaticNodeReverse2(Node head) {if(Head = =NULL){returnHead } Node pre = head; Node cur = head.getnextnode (); Node Next; while(cur! =NULL) {next = Cur.getnextnode (); Cur.setnextnode (pre); Pre = cur; cur = next; }//Set the next node of the original list's head node to NULL, then assign the inverted head node to the headHead.setnextnode (NULL); head = Pre;returnHead }}
GitHub Source Address
https://github.com/GeniusVJR/Algorithm-and-Data-Structure/tree/master/to realize the reversal of the list
[Algorithm] for single-linked list inversion