链表中的重用代码

  1. 反转链表;固定的while循环
while(head != null){
    
    
    next = head.next;  // 记住下一个节点
    head.next = pre; // 改变指向
    pre = head; // 记住前一个节点
    head = next; // head 向下移动
}
  1. 删除某个固定的节点【需要判断是不是删除头节点】;
// 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. 判断单链表是否有环
while (slow != fast) {
    
     // 相遇时退出
     if (fast == null || fast.next == null) {
    
     // 快指针先到达尾部
         return false;
     }
     slow = slow.next; // 走1步
     fast = fast.next.next; // 走2步
}
  1. 找到中间节点;n1 = n1.next; n2 = n2.next.next;走一步走两步的技巧
while (slow != fast) {
    
     // 相遇时退出
     if (fast == null || fast.next == null) {
    
     // 快指针先到达尾部
         return false;
     }
     slow = slow.next; // 走1步
     fast = fast.next.next; // 走2步
}
  1. 有时候可以使用一个假的头节点,来解决头节点被删除和改变的可能
Node fakeNode = new Node(-1);

猜你喜欢

转载自blog.csdn.net/weixin_39443483/article/details/112316079