Skip to content

Commit a34bc59

Browse files
Linked List Programs
1 parent 0fb8dfe commit a34bc59

8 files changed

+663
-0
lines changed

Linked Lists/DoublyLinkedList.py

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# Author: AKHILESH SANTOSHWAR
2+
3+
class Node(object):
4+
# Each node has its data and a pointer that points to next node in the Linked List
5+
def __init__(self, data, next = None, previous = None):
6+
self.data = data;
7+
self.next = next;
8+
self.previous = previous
9+
10+
class DoublyLinkedList(object):
11+
def __init__(self):
12+
self.head = None
13+
14+
# for inserting at beginning of linked list
15+
def insertAtStart(self, data):
16+
if self.head == None:
17+
newNode = Node(data)
18+
self.head = newNode
19+
else:
20+
newNode = Node(data)
21+
self.head.previous = newNode
22+
newNode.next = self.head
23+
self.head = newNode
24+
25+
# for inserting at end of linked list
26+
def insertAtEnd(self, data):
27+
newNode = Node(data)
28+
temp = self.head
29+
while(temp.next != None):
30+
temp = temp.next
31+
temp.next = newNode
32+
newNode.previous = temp
33+
34+
# deleting a node from linked list
35+
def delete(self, data):
36+
temp = self.head
37+
if(temp.next != None):
38+
# if head node is to be deleted
39+
if(temp.data == data):
40+
temp.next.previous = None
41+
self.head = temp.next
42+
temp.next = None
43+
return
44+
else:
45+
while(temp.next != None):
46+
if(temp.data == data):
47+
break
48+
temp = temp.next
49+
if(temp.next):
50+
# if element to be deleted is in between
51+
temp.previous.next = temp.next
52+
temp.next.previous = temp.previous
53+
temp.next = None
54+
temp.previous = None
55+
else:
56+
# if element to be deleted is the last element
57+
temp.previous.next = None
58+
temp.previous = None
59+
return
60+
61+
if (temp == None):
62+
return
63+
64+
# for printing the contents of linked lists
65+
def printdll(self):
66+
temp = self.head
67+
while(temp != None):
68+
print(temp.data, end=' ')
69+
temp = temp.next
70+
71+
if __name__ == '__main__':
72+
dll = DoublyLinkedList()
73+
dll.insertAtStart(1)
74+
dll.insertAtStart(2)
75+
dll.insertAtEnd(3)
76+
dll.insertAtStart(4)
77+
dll.printdll()
78+
dll.delete(2)
79+
print()
80+
dll.printdll()

0 commit comments

Comments
 (0)