-
Notifications
You must be signed in to change notification settings - Fork 438
/
DoublyLinkedList.py
80 lines (72 loc) · 2.34 KB
/
DoublyLinkedList.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
# Author: OMKAR PATHAK
class Node(object):
# Each node has its data and a pointer that points to next node in the Linked List
def __init__(self, data, next = None, previous = None):
self.data = data;
self.next = next;
self.previous = previous
class DoublyLinkedList(object):
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
# for printing the contents of linked lists
def printdll(self):
temp = self.head
while(temp != None):
print(temp.data, end=' ')
temp = temp.next
if __name__ == '__main__':
dll = DoublyLinkedList()
dll.insertAtStart(1)
dll.insertAtStart(2)
dll.insertAtEnd(3)
dll.insertAtStart(4)
dll.printdll()
dll.delete(2)
print()
dll.printdll()