-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.py
More file actions
78 lines (65 loc) · 2.04 KB
/
LinkedList.py
File metadata and controls
78 lines (65 loc) · 2.04 KB
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
72
73
74
75
76
77
78
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
# O(n) time | O(1) space
def iterativeInsertAtEnd(self, valueToInsert):
if self.head is None:
self.head = Node(valueToInsert)
else:
current = self.head
while current.next is not None:
current = current.next
current.next = Node(valueToInsert)
def insertAtBeginning(self, valueToInsert):
if self.head is None:
self.head = Node(valueToInsert)
else:
newHead = Node(valueToInsert)
newHead.next = self.head
self.head = newHead
# O(n) time | O(1) space
def iterativePrint(self):
print("Linked list iterative print")
current = self.head
while current:
print(current.value)
current = current.next
# O(n) time | O(1) space
def iterativeReverse(self):
prev, current = None, self.head
while current is not None:
temp = current.next
current.next = prev
prev = current
current = temp
self.head = prev
# O(n) time | O(n) space
def recursiveReverse(self):
print('Linked list recursive reverse')
def reverse(curr, prev):
if curr is None:
return prev
else:
next = curr.next
curr.next = prev
return reverse(next, curr)
self.head = reverse(self.head, None)
def detectCycle(self):
fast, slow = self.head, self.head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
if __name__ == '__main__':
List = LinkedList()
List.iterativeInsertAtEnd(10)
List.iterativeInsertAtEnd(11)
List.iterativePrint()
List.recursiveReverse()
List.iterativePrint()