-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathdoubly linked list.py
52 lines (47 loc) · 1.36 KB
/
doubly 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
class Node:
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self, object):
self.tail = self.head = Node(object)
def append(self, object):
c = self.tail
self.tail.next = Node(object)
self.tail = self.tail.next
self.tail.prev = c
def insert(self, index, object):
new_node = Node(object)
if index == 0:
ll = new_node
self.head.prev = ll
ll.next = self.head
self.head = ll
else:
current_indx = 0
ll = self.head
while current_indx < index - 1:
ll = ll.next
current_indx += 1
ll.next.prev = new_node
new_node.next = ll.next
ll.next = new_node
new_node.prev = ll
def pop(self):
curr = self.head
while curr.next.next != None:
curr = curr.next
self.tail = curr
self.tail.next = None
def show(self, reverse = False):
if reverse:
curr = self.tail
while curr:
print(curr.value)
curr = curr.prev
else:
curr = self.head
while curr:
print(curr.value)
curr = curr.next