[Leetcode][python]Linked List Cycle/Linked List Cycle II

来源:互联网 发布:淘宝 授权怎么弄啊 编辑:程序博客网 时间:2024/05/21 19:23

Linked List Cycle

题目大意

判断一个链表中是否存在着一个环,能否在不申请额外空间的前提下完成?

解题思路

快慢指针

代码

class Solution(object):    def hasCycle(self, head):        """        :type head: ListNode        :rtype: bool        """        slow = fast = head        while fast and fast.next:            slow = slow.next            fast = fast.next.next            if slow == fast:                return True        return False

Linked List Cycle II

题目大意

如果给定的单向链表中存在环,则返回环起始的位置,否则返回为空。最好不要申请额外的空间。

解题思路

详见:
https://shenjie1993.gitbooks.io/leetcode-python/142%20Linked%20List%20Cycle%20II.html
这里写图片描述

代码

class Solution(object):    def detectCycle(self, head):        """        :type head: ListNode        :rtype: ListNode        """        slow = fast = head        while fast and fast.next:            slow = slow.next            fast = fast.next.next            if slow == fast:                node = head                while node != slow:  # 到达C点新指针node从head开始走                    node = node.next                    slow = slow.next                return node        return None

总结

思路题

原创粉丝点击