forked from TonnyL/Windary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedListCycle.py
42 lines (35 loc) · 911 Bytes
/
LinkedListCycle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# Given a linked list, determine if it has a cycle in it.
#
# Follow up:
# Can you solve it without using extra space?
#
#
class LinkedListCycle:
# Time limit exceed.
# def hasCycle(self, head):
# """
# :type head: ListNode
# :rtype: bool
# """
# if head is None or head.next is None:
# return False
# node = head.next
# while node != head:
# if node is None:
# return False
# node = node.next
#
# return True
# Accepted.
def hasCycle(self, head):
slow, fast = head, head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
class ListNode:
def __init__(self, x):
self.val = x
self.next = None