[题解][LeetCode][Linked List Cycle II]

题目:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

题解1:

依次检查每一个节点。检查的某点的时候,从头开始扫描,看是否能找到一个点,这个点是这个点的next。直到扫描到这个点本身时停止。

* 如果在扫描结束前(即,扫描到这个点本身之前),找到一个点,是这个点的next,这说明我们正在检查的点是链表的尾节点,而我们扫描到的这点正是尾节点循环指回链表指到的那个点。我们需要输出的就是这个点(尾节点)的next


Code1:

class Solution:
    # @param head, a ListNode
    # @return a list node
    def check(self, head, pc):
        p = head
        while not(p is pc):
            if p is pc.next:
                return True
            p = p.next
        if p is pc.next:
            return True
        else:
            return False

    def detectCycle(self, head):
        if head is None:
            return None

        pc = head.next
        while not(pc is None):
            if self.check(head, pc):
                return pc.next
            pc = pc.next
            
        return None


经检验,这个算法...超时


题解2:

我们解决这个问题的第一个版本,用的是快慢指针的方法。

我们也可以通过这个方法来求借。

我们通过快慢指针能得到的是相遇点,题设给的是头节点。我们要求的是尾节点指回链表的那个节点(称其为目标节点)。

我们现在需要做的就是理清三个节点之间的关系,看图:



我们知道三个点之间的关系之后,代码就很好写了。

两指针相遇之后,将快指针重置指向头结点,慢指针保持指向相遇点。然后两个指针同时开始一步步走,两个指针再次相遇的时候,就是我们所要找的目标节点。


Code2:

class Solution:
    def detectCycle(self, head):
        if (head is None) or (head.next is None):
            return None
        p1 = head
        p2 = head
        
        while (p2 and p2.next):
            p1 = p1.next
            p2 = p2.next.next
            if (p1 is p2):
                break

        if (p1 is p2):
            p2 = head
            while not(p1 is p2):
                p1 = p1.next
                p2 = p2.next
            return p1

        return None


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值