标签:
判断一个链表中是否存在着一个环,能否在不申请额外空间的前提下完成?
注意点:
例子:
输入:
1->2->3
| |
5<-4
输出: True
沿着链表不断遍历下去,如果遇到空节点就说明该链表不存在环。但如果存在环,这样的遍历就会进入死循环。在环上前进会不断地绕圈子,我们让两个速度不同的指针绕着环前进,那么早晚速度快的那个将追上速度慢的,所以如果速度快的追上了速度慢的,那么该链表就存在环,循环终止。
# 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) 来获得相关源码。
标签:
原文地址:http://blog.csdn.net/u013291394/article/details/51334790