# Delete N nodes from end of doubly linked list python

Python program for Delete N nodes from end of doubly linked list. Here problem description and other solutions.

``````#  Python 3 program for
#  Delete last N nodes in doubly linked list
def __init__(self, data) :
self.data = data
self.next = None
self.prev = None

def __init__(self) :
self.tail = None

#  Insert new node at end position
def insert(self, value) :
#  Create a node
self.tail = node
return

#  Add node at last position
self.tail.next = node
node.prev = self.tail
self.tail = node

#  Display node element of doubly linked list
def display(self) :
else :
#  Get first node of linked list
while (temp != None) :
#  Display node value
print("", temp.data, end = " ")
#  Visit to next node
temp = temp.next

#  Get last node of linked list
temp = self.tail
while (temp != None) :
#  Display node value
print("", temp.data, end = " ")
#  Visit to prev node
temp = temp.prev

print(end = "\n")

def deleteLastN(self, n) :
if (self.head == None or n <= 0) :
return

counter = 0
#  check n nodes exist or not
while (temp != None and counter < n) :
counter += 1
temp = temp.next

if (counter >= n) :
#  Get last node
temp = self.tail
counter = n
while (self.tail != None and counter > 0) :
temp = self.tail
self.tail = temp.prev
temp.next = None
temp.prev = None
#  remove first node

counter -= 1

if (self.tail != None) :
self.tail.next = None

else :
print("Deleted ", n ," node are missing")

def main() :
dll.insert(1)
dll.insert(2)
dll.insert(3)
dll.insert(4)
dll.insert(5)
dll.insert(6)
dll.insert(7)
dll.insert(8)
print("\nBefore delete", end = "")
dll.display()
n = 5
dll.deleteLastN(n)
print("\nAfter delete last ", n ," Nodes")
dll.display()

if __name__ == "__main__": main()``````

Output

``````Before delete
Linked List Head to Tail  :  1  2  3  4  5  6  7  8
Linked List Tail to Head  :  8  7  6  5  4  3  2  1

After delete last  5  Nodes