Doubly Linked List in Python:
Insertion in Doubly Linked-list
For each insertion operation, we need to consider the three cases. These three cases also need to be
considered when removing data from the doubly linked list.
• Insertion at the beginning
• Insertion at end
• Insertion at Nth position
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
def insertLast(head, data):
new_node = Node(data)
new_node.next = None
if head is None:
head = new_node
new_node.prev = None
return
temp = head
while temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.prev = temp
def insertStart(head, data):
new_node = Node(data)
new_node.next = head
new_node.prev = None
if head is not None:
head.prev = new_node
head = new_node
def calcSize(node):
size = 0
while node is not None:
node = node.next
size += 1
return size
def insertPosition(pos, data, head):
size = calcSize(head)
if pos < 0 or pos > size:
print("Can't insert, {} is not a valid position".format(pos))
return
if pos == 0:
insertStart(head, data)
elif pos == size:
insertLast(head, data)
else:
temp = head
new_node = Node(data)
new_node.next = None
while pos > 0:
temp = temp.next
pos -= 1
temp2 = temp.next
new_node.next = temp2
new_node.prev = temp
temp.next = new_node
temp2.prev = new_node
def display(node):
end = None
print("List in Forward direction:", end=" ")
while node is not None:
print(node.data, end=" ")
end = node
node = node.next
print("\nList in backward direction:", end=" ")
while end is not None:
print(end.data, end=" ")
end = end.prev
head = None
insertStart(head, 12)
insertStart(head, 16)
insertStart(head, 20)
insertLast(head, 10)
insertLast(head, 14)
insertLast(head, 18)
insertLast(head, 11)
print("Linked list before insertion at specific position")
display(head)
print("\n\nLinked list after insertion at specific position")
insertPosition(3, 25, head)
display(head)