-
Notifications
You must be signed in to change notification settings - Fork 1
/
doubly_linked_list.py
76 lines (66 loc) · 2.22 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
class node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
class doubly_linked_list:
def __init__(self):
self.head = None
# for inserting at beginning of linked list
def insertAtStart(self, data):
if self.head == None:
newnode = node(data)
self.head = newnode
else:
newnode = node(data)
self.head.previous = newnode
newnode.next = self.head
self.head = newnode
# for inserting at end of linked list
def insertAtEnd(self, data):
newnode = node(data)
temp = self.head
while(temp.next != None):
temp = temp.next
temp.next = newnode
newnode.previous = temp
# deleting a node from linked list
def delete(self, data):
temp = self.head
if(temp.next != None):
# if head node is to be deleted
if(temp.data == data):
temp.next.previous = None
self.head = temp.next
temp.next = None
return
else:
while(temp.next != None):
if(temp.data == data):
break
temp = temp.next
if(temp.next):
# if element to be deleted is in between
temp.previous.next = temp.next
temp.next.previous = temp.previous
temp.next = None
temp.previous = None
else:
# if element to be deleted is the last element
temp.previous.next = None
temp.previous = None
return
if (temp == None):
return
def print_all(self):
temp = self.head
while(temp != None):
print(temp.data, end=' ')
temp = temp.next
if __name__ == '__main__':
doubly_linked_list = doubly_linked_list()
doubly_linked_list.insertAtStart(1.5)
doubly_linked_list.insertAtStart(2.4)
doubly_linked_list.insertAtEnd(30)
doubly_linked_list.insertAtStart(4.3)
doubly_linked_list.print_all()