Reusable code in the linked list

  1. Reverse linked list; fixed while loop
while(head != null){
    
    
    next = head.next;  // 记住下一个节点
    head.next = pre; // 改变指向
    pre = head; // 记住前一个节点
    head = next; // head 向下移动
}
  1. Delete a fixed node [need to determine whether to delete the head node];
// 1.可以做一个假的头节点
Node preHead = new Node(-1);
preHead.next = head;

// 2.分条件讨论

// 删除某个节点需要记住要删除的前一个节点
pre = ...;
if (head.vaule == ...){
    
    
	pre.next = pre.next.next;
}

public static Node removeValue(Node head, int num){
    
    
        while (head != null){
    
    
            // 找到一个值不等于num的节点
            if (head.value != num){
    
    
                break;
            }
            head = head.next;
        }
        Node pre = head;
        Node cur = head;

        // 这段代码是遍历链表删除某个值的核心代码
        while(cur != null){
    
    
            if (cur.value == num){
    
    
                pre.next = cur.next;
            } else {
    
    
                pre = cur;
            }
            cur = cur.next;
        }
}
  1. Determine whether the singly linked list has a ring
while (slow != fast) {
    
     // 相遇时退出
     if (fast == null || fast.next == null) {
    
     // 快指针先到达尾部
         return false;
     }
     slow = slow.next; // 走1步
     fast = fast.next.next; // 走2步
}
  1. Find the intermediate node; n1 = n1.next; n2 = n2.next.next; Take one step and two steps
while (slow != fast) {
    
     // 相遇时退出
     if (fast == null || fast.next == null) {
    
     // 快指针先到达尾部
         return false;
     }
     slow = slow.next; // 走1步
     fast = fast.next.next; // 走2步
}
  1. Sometimes a fake head node can be used to solve the possibility of the head node being deleted and changed
Node fakeNode = new Node(-1);

Guess you like

Origin blog.csdn.net/weixin_39443483/article/details/112316079