class node:
def __init__(self, next=None, prev=None, value=None):
self.next = next # reference to next node
self.prev = prev # reference to previous node
self.value = value
class DoublyLinkedList:
def __init__(self):
self.start=None
def insert_at_first(self, value):
# Node & assign the value
newnode = node(value = value)
# Make next of newnode as start and prevs as NULL
newnode.next = self.start
newnode.prev = None
# change prev of start node to newnode
if self.start!=None:
self.start.prev = newnode
# move the start to point to the newnode
self.start = newnode
def insert_after(self, prev, value):
if prev==None: # check if the given prev_node is NULL
print("This node doesn't exist ")
return
#allocate node & assign value
newnode = node(value =value)
# Make next of new node as next of prevnode
newnode.next = prev.next
# Make the next of prevnode as newnode
prev.next = newnode
# Make prevnode as previous of newnode
newnode.prev = prev
# Change previous of new_node's next node
if newnode.next is not None:
newnode.next.prev = newnode
def insert_at_end(self, value):
# create node and assign value
newnode = node(value = value)
last = self.start
# new node is going to be the last node, so make next of it as NULL
newnode.next = None
# If the Linked List is empty, then make the new node as head
if self.start is None:
newnode.prev = None
self.start = newnode
return
# Else traverse till the last node
while (last.next is not None):
last = last.next
# Change the next of last node
last.next = newnode
# Make last node as previous of new node
newnode.prev = last
def delete_node(self, node_to_del):
if self.start is None or node_to_del is None:
return
# If node to be deleted is head node
if self.start == node_to_del:
self.start = node_to_del.next
# Change next only if node to be deleted is NOT
# the last node
if node_to_del.next is not None:
node_to_del.next.prev = node_to_del.prev
# Change prev only if node to be deleted is NOT first node
if node_to_del.prev is not None:
node_to_del.prev.next = node_to_del.next
def display(self, node):
print("linked list ")
while(node is not None):
print(node.value)
last = node
node = node.next
print("\n reverse linked list ")
while(last is not None):
print(last.value)
last = last.prev
llist = DoublyLinkedList()
llist.insert_at_end(6)
llist.insert_at_end(2)
llist.insert_at_end(3)
llist.insert_at_first(7)
llist.insert_at_first(5)
llist.insert_at_first(1)
llist.insert_at_end(4)
llist.insert_after(llist.start.next, 8)
llist.delete_node(llist.start)
llist.delete_node(llist.start.next)
llist.display(llist.start)
|