-
Notifications
You must be signed in to change notification settings - Fork 0
/
141. Linked List Cycle.py
43 lines (37 loc) · 1.01 KB
/
141. Linked List Cycle.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
43
# Given a linked list, determine if it has a cycle in it.
#
# Follow up:
# Can you solve it without using extra space?
# 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
"""
while head:
if head.val == None:
return True
head.val = None
head = head.next
return False
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None or head.next == None:
return False
walk = head
run = head.next
while walk != run:
walk = walk.next
if run.next == None or run.next.next == None:
return False
run = run.next.next
return True