-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathDoubly_Linked_List.py
80 lines (63 loc) · 1.48 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
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
79
80
# Doubly Linked List with implementation
# insert at any side
# print in any direction
class Node:
def __init__(self, data=None, prev=None, next=None):
self.data = data
self.prev = prev
self.next = next
class DoublyLinkedList:
def __init__(self):
self.head = None
def insert_at_beginning(self, data):
self.head = Node(data, next=self.head)
self.head.next.prev = self.head
return
def insert_at_end(self, data):
if self.head == None:
self.head = Node(data, next=self.head)
return
itr=self.head
while itr:
if(itr.next==None):
itr.next = Node(data, prev=itr)
break
itr = itr.next
return
def print_forward(self):
if self.head is None:
print("Linked list is empty")
return
itr=self.head
while itr:
print(str(itr.data) + " <-->", end=" ")
itr = itr.next
print(" ")
return
def print_backward(self):
if self.head is None:
print("Linked list is empty")
return
itr=self.head
while itr.next:
itr = itr.next
while itr:
print( str(itr.data) + " <-->", end=" ")
itr=itr.prev
print(" ")
return
# Main Code
if __name__ == '__main__':
ll = DoublyLinkedList()
ll.insert_at_end("How")
ll.insert_at_end("are")
ll.insert_at_end("you ?")
print("3 words appended to the end of the list :")
ll.print_forward()
print(" ")
ll.insert_at_beginning("Hello,")
print("1 word added at the beginning")
ll.print_forward()
print(" ")
print("Printing the Doubly Linked List backwards :")
ll.print_backward()