原题地址:https://leetcode.com/problems/linked-list-cycle/description/
题目描述:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题解:判断一个单项链表是否有环,声明两个指针都指向链表头,然后同时开始遍历。
其中一个指针每次走一步,另一个每次走两步,如果链表存在环,则两个指针迟早会相遇。
此时走的快的指针比走的慢的指针多走了n圈。
假设非环部分长度为a, 换部分长度为b, a+b = n,当慢指针进入环时,循环了a次。假设此时慢指针距离快指针x,即快指针距离慢指针b-x,每次快指针可以缩短1的距离,需要b-x次循环,两者相遇。
a + b - x < a+b = n, 时间复杂度O(n)。
# 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
"""
a = b = head
while (a is not None and b is not None):
a = a.next
if b.next is not None:
b = b.next.next
else:
return False
if a == b:
return True
return False
16 / 16 test cases passed.
Status: Accepted
Runtime: 63 ms