代码随想录day4:链表part2,快慢指针两种用法,链表模拟基本功

本文介绍了链表操作的四个问题:24.两两交换链表节点、19.删除链表倒数第N个节点、160.链表相交和142.环形链表II,涉及基础编码技巧和快慢指针的不同应用场景。
摘要由CSDN通过智能技术生成

day4 链表part2:交换&倒删&相交

24.两两交换链表中的节点

链表的模拟操作考验coding基本功,画图模拟,想清楚步骤123,注意先后顺序!

/**
 * 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 swapPairs(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;
        // (first, second) 交换成 (second, first)
        // 此时的first是下一组(first, second)的pre
        ListNode first, second;
        while (pre.next != null && pre.next.next != null) {
            first = pre.next;
            second = first.next;
            pre.next = second;
            first.next = second.next;
            second.next = first;
            pre = first;
        }
        return dummy.next;
    }
}

19.删除链表的倒数第 N 个结点

快慢指针的一种用法——快指针先走,快慢指针维持固定距离

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode slow = dummy, fast = dummy;
        while (n-- > 0) fast = fast.next;
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}

160.链表相交

两条链表分别走到尾再从另一支开始走到公共节点的距离是一样的

如果没有公共节点,两个指针会同时走到另一支尾部空节点处

两种情况两个指针都会相等,都能跳出循环

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode curA = headA, curB = headB;
        while (curA != curB) {
            curA = curA == null ? headB : curA.next;
            curB = curB == null ? headA : curB.next;
        }
        return curA;
    }
}

142.环形链表 II

快慢指针的另外一种用法——快指针走的比慢指针快,相对速度为1时,一定会相遇(有环情况)

环相交位置与入口位置关系详细数学解释见代码随想录文章 https://programmercarl.com/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.html#%E6%80%9D%E8%B7%AF

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null || head.next == null || head.next.next == null)
            return null;
        ListNode slow = head.next, fast = slow.next;
        while (fast != slow) {
            // 无环退出
            if (fast.next == null || fast.next.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
        }
        // 有环出循环
        // fast回到头节点,与slow相同速度移动
        fast = head;
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值