-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.py
71 lines (62 loc) · 2.08 KB
/
linked_list.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class ListNode():
def __init__(self, val, next=None):
self.val = val
self.next = next
def contains_cycle(self):
# the list is only 1 node long, which cannot contain a cycle
if not self.next:
return False
slow_pointer = self.next
fast_pointer = self.next.next
while slow_pointer is not fast_pointer:
if slow_pointer:
slow_pointer = slow_pointer.next
if fast_pointer and fast_pointer.next:
fast_pointer = fast_pointer.next.next
if slow_pointer is None:
return False
else:
return True
def get_beginning_of_cycle_if_exists(self):
# the list is only 1 node long, which cannot contain a cycle
if not self.next:
return None
slow_pointer = self.next
fast_pointer = self.next.next
while slow_pointer is not fast_pointer:
if slow_pointer:
slow_pointer = slow_pointer.next
if fast_pointer and fast_pointer.next:
fast_pointer = fast_pointer.next.next
if slow_pointer is None:
return None
# reset slow pointer
slow_pointer = self
# move the pointers again at same speed, will meet at start
while slow_pointer is not fast_pointer:
# print(slow_pointer.val, fast_pointer.val)
slow_pointer = slow_pointer.next
fast_pointer = fast_pointer.next
return slow_pointer
def reverse(self):
prev = None
head = self
while head.next:
next_node = head.next
head.next = prev
prev = head
head = next_node
head.next = prev
return head
def reverse_recursive(self):
def rev(node):
if not node.next:
rev.head = node
return
rev(node.next)
temp = node.next
temp.next = node
node.next = None
rev.head = self
rev(self)
return rev.head