首页 > 其他 > 详细

LeetCode Linked List Cycle

时间:2016-05-07 09:03:46      阅读:268      评论:0      收藏:0      [点我收藏+]

LeetCode解题之Linked List Cycle


原题

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

注意点:

例子:

输入:

1->2->3
  |  |
  5<-4

输出: True

解题思路

沿着链表不断遍历下去,如果遇到空节点就说明该链表不存在环。但如果存在环,这样的遍历就会进入死循环。在环上前进会不断地绕圈子,我们让两个速度不同的指针绕着环前进,那么早晚速度快的那个将追上速度慢的,所以如果速度快的追上了速度慢的,那么该链表就存在环,循环终止。

AC源码

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


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


if __name__ == "__main__":
    None

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

LeetCode Linked List Cycle

原文:http://blog.csdn.net/u013291394/article/details/51334790

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!