The reversal of a single-linked list is relatively simple, and iterative and recursive can be done.
Define a class to represent the nodes in a single-linked list:
public class ListNode {private int val;private listnode next;public listnode (int value) {this.val = Value;this.next = null; }public int Getval () {return val;} public void Setval (int val) {this.val = val;} Public ListNode GetNext () {return next;} public void Setnext (ListNode next) {This.next = Next;}}
Iterative methods:
/** * Traversal, the double pointer moves to the tail at the same time. * @param head node of the linked list to be reversed * @return */public static ListNode reverse (ListNode head) {if (head==null) { return head;} ListNode pre = head; The previous pointer listnode cur = head.getnext (); The latter pointer ListNode next;//the temporary object, the while (cur! = null) to use when the pointer moves back, {next = Cur.getnext (); Cur.setnext (pre);p re = cur;//pointer back cur = next;//pointer back}//Be sure to remember to set the next null for the initial link header node, since it will be the last node Head.setnext (null) after the reversal, and//The head node is set to the first node of the inverted list, then back to Okhead = pre; return head;}
Recursive method:
/** * Recursive thought * before flipping the current node, if the node has subsequent nodes, flip its successor node first * If the node has no child nodes, then point the node's next to its parent node and the parent node's next to NULL * @param head * @return */public Static ListNode reverse (ListNode head) {//current node is null, or the current node has no subsequent nodes, recursion exits if (Head.getnext () ==null | | head==null) {return Head;} When the current node is not NULL and has next, recursion reverses its subsequent node listnode tempnode = reverse (Head.getnext ());//Reverses the current node and its child nodes Head.getnext (). Setnext ( Head); Head.setnext (null); return tempnode;}
Test function:
public static void Main (string[] args) {ListNode Node1 = new ListNode (1); ListNode node2 = new ListNode (2); ListNode node3 = new ListNode (3); ListNode node4 = new ListNode (4); Node1.setnext (Node2); Node2.setnext (NODE3); Node3.setnext (node4); node1 = Reverse ( Node1); while (node1! = null) {System.out.print (Node1.getval () + ""); Node1 = Node1.getnext ();}}
java-reverse single-linked list