-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedLists.py
72 lines (50 loc) · 1.59 KB
/
LinkedLists.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
72
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = self.head
self.length = 0
def add_last(self, node):
new_node = node
if self.head is None:
self.head = new_node
self.tail = new_node
self.length += 1
else:
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node
self.tail.next = None
self.length += 1
def add_first(self, node):
new_node = node
if self.head is None:
self.head = new_node
self.tail = new_node
self.length += 1
else:
new_node.prev = None
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
self.length += 1
def delete_last(self):
self.length -= 1
if self.tail is not None:
self.tail = self.tail.prev
self.tail.next = None
def delete_first(self):
self.head = self.head.next
self.head.prev = None
self.length -= 1
def get_at_pos(self, pos):
count = 0
curr_node = self.head
while curr_node is not None:
if count != pos:
# Fetch the next node
curr_node = curr_node.next
count += 1
else:
return curr_node
print("The specified position is invalid! Could not find Node. ")
return None