Unidirectional linked list inversion

Time:2022-5-10

Unidirectional linked list inversion

First create a one-way linked list

/**
 *Unidirectional linked list * * / class node{
    public Node(int value){
        this.value = value;
 }
    public int value;
 public Node next;
}
  • Head insertion

The head insertion method uses the double pointer method for head insertion

/**
 *Method 1 * @ param head
 * @return
 */
public  static Node reverse1(Node head){
    /**
 *Judge whether the current node is empty or has only one node 
 */ 
 if (head == null || head.next == null) {
        return head;
 }
 //Record the node of the last cur
 Node pre = null;
 //Record the next node of the current node
 Node post;
 while (head!=null){
 //Move the post node forward
 post = head.next;
 //The next node of the current node points to the previous current node
 head.next = pre;
 //Assign the current node to pre for next use
 pre = head;
 //Move the current node forward
 head = post;
 }
    //Since head = post has been moved forward in the last loop, pre is taken here as the inverted linked list
 return pre;
}
  • Recursive inversion
/**
 *Method 2, recursive * @ param head
 * @return
 */
public  static Node reverse2(Node head){
 /**
 *Judge whether the current node is empty or has only one node 
 */ 
 if (head == null || head.next == null) {
        return head;
 }
 /**
 *Get the next node recursively, and the node returned at the bottom is the tail of the linked list 
 */
 Node node = reverse2(head.next);
 /**
 *Reverse here
 */ 
 head.next.next = head;
 head.next = null;
 return node;
}