Linked List Cycle
Question
- leetcode: Linked List Cycle | LeetCode OJ
- lintcode: (102) Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Example
Given -21->10->4->5, tail connects to node index 1, return true
Challenge
Follow up:
Can you solve it without using extra space?
题解 - 快慢指针
对于带环链表的检测,效率较高且易于实现的一种方式为使用快慢指针。快指针每次走两步,慢指针每次走一步,如果快慢指针相遇(快慢指针所指内存为同一区域)则有环,否则快指针会一直走到NULL
为止退出循环,返回false
.
快指针走到NULL
退出循环即可确定此链表一定无环这个很好理解。那么带环的链表快慢指针一定会相遇吗?先来看看下图。
在有环的情况下,最终快慢指针一定都走在环内,加入第i
次遍历时快指针还需要k
步才能追上慢指针,由于快指针比慢指针每次多走一步。那么每遍历一次快慢指针间的间距都会减少1,直至最终相遇。故快慢指针相遇一定能确定该链表有环。
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: True if it has a cycle, or false
"""
def hasCycle(self, head):
# write your code here
if head is None:
return False
p1 = head
p2 = head
while True:
if p1.next is not None:
p1=p1.next.next
p2=p2.next
if p1 is None or p2 is None:
return False
elif p1 == p2:
return True
else:
return False
return False
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
if head == None or head.next == None:
return False
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
复杂度分析
- 在无环时,快指针每次走两步走到尾部节点,遍历的时间复杂度为 $$O(n/2)$$.
- 有环时,最坏的时间复杂度近似为 $$O(n)$$. 最坏情况下链表的头尾相接,此时快指针恰好在慢指针前一个节点,还需 n 次快慢指针相遇。最好情况和无环相同,尾节点出现环。
故总的时间复杂度可近似为 $$O(n)$$.