Skip to content

Commit ff2adb2

Browse files
author
weiy
committed
linked list cycle O(1) space solution
1 parent 92cf627 commit ff2adb2

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Diff for: Array/LinkedListCycle.py

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
3+
Given a linked list, determine if it has a cycle in it.
4+
5+
Follow up:
6+
Can you solve it without using extra space?
7+
8+
基本思路:
9+
10+
形成环就是后面的节点中的next指向了前面出现过的节点。
11+
下面这个用了额外空间。
12+
13+
改进:
14+
使用 O(1) 空间的解决方法:
15+
思路是两个指针:
16+
一个每次走一步,另一个每次走两步,若有一个环,那么走两步的与走一步的会在走过这个环的长度后相遇。
17+
相当于两个人跑步,一个每秒跑两米,一个跑一米,绕着100米的圆形跑,100秒过后,一米的这个跑了一圈,二米的这个跑了两圈,但它们相遇了。
18+
19+
20+
测试地址:
21+
https://leetcode.com/problems/linked-list-cycle/description/
22+
23+
"""
24+
25+
# Definition for singly-linked list.
26+
# class ListNode(object):
27+
# def __init__(self, x):
28+
# self.val = x
29+
# self.next = None
30+
31+
class Solution(object):
32+
def hasCycle(self, head):
33+
"""
34+
:type head: ListNode
35+
:rtype: bool
36+
"""
37+
38+
# while head:
39+
# if hasattr(head, 'hasVisited'):
40+
# return True
41+
42+
# head.hasVisited = True
43+
# head = head.next
44+
# return False
45+
46+
if not head:
47+
return False
48+
49+
two_head = head.next
50+
51+
if not two_head:
52+
return False
53+
54+
while head != None and two_head != None:
55+
56+
if head == two_head:
57+
return True
58+
59+
head = head.next
60+
try:
61+
two_head = two_head.next.next
62+
except:
63+
return False
64+
65+
return False
66+

0 commit comments

Comments
 (0)