链表中环的问题和双向链表

1.链表中环的问题

先按照快慢指针方法寻找相遇位置,然后将两指针分别放在链表头和相遇位置,并改为相同速度推进,则两指针在环开始位置相遇

Java实现:双指针法

    public static ListNode detectCycleByTwoPoint(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode slow = head, fast = head;
        while (fast != null) {
            slow = slow.next;
            if (fast.next != null) {
                fast = fast.next.next;
            } else {
                return null;
            }
            if (fast == slow) {
                ListNode ptr = head;
                while (ptr != slow) {
                    ptr = ptr.next;
                    slow = slow.next;
                }
                return ptr;
            }
        }
        return null;
    }

python实现

    # 确定环的入口
    def detectCycle(self, head):
        fast, slow = head, head
        while True:
            if not (fast and fast.next): return
            fast, slow = fast.next.next, slow.next
            if fast == slow: break
        fast = head
        while fast != slow:
            fast, slow = fast.next, slow.next
        return fast

2.双向链表

略。。。

你可能感兴趣的:(算法打卡,链表,数据结构)