算法训练营day05 链表(双指针、快慢指针)

💡 解题思路

  1. 📝 确定输入与输出
  2. 🔍 分析复杂度
  3. 🔨 复杂题目拆分严谨且完整 地拆分为更小的子问题(链表注意:循环、找规律)–(多总结
  4. 💭 选择处理逻辑: 根据拆分后的子问题,总结并选择合适的问题处理思路
  5. 🔎 检查特殊情况:边界条件和特殊情况
  6. 🏁 返回结果

19. 删除链表的倒数第 N 个结点快慢指针

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode fast = head;
        ListNode slow = new ListNode(0);
        slow.next = head; 
        ListNode res = slow;
        while(fast != null) {
            if (n > 0) {
                n--;
            } else {
                slow = slow.next;
            }
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return res.next;
    }
}

面试题 02.07. 链表相交双指针

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;
        ListNode headA1 = headA, headB1 = headB;
        while(headA1 != headB1) {
            if (headA1 != null) headA1 = headA1.next;
            else headA1 = headB;
            if (headB1 != null) headB1 = headB1.next;
            else headB1 = headA;
        }
        return headA1;
    }
}

142. 环形链表 II (快慢指针)
思路:当有环,快慢指针相遇时,慢指针距离入环节点位置+(n-1)圈(环)= 指针头结点到入环节点距离

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) return null;
        ListNode fast = head, slow = head;
        while (fast != null) {
            if (fast.next == null) return null;
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                ListNode temp = head;
                while(temp != slow) {
                    temp = temp.next;
                    slow = slow.next;
                }
                return temp;
            }
        }
        return null;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值