Posted on by Kalkicode
Code Doubly linked list

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
class LinkNode :
	def __init__(self, data) :
		self.data = data
		self.next = None
		self.prev = None
	

class DoublyLinkedList :
	def __init__(self) :
		self.head = None
		self.tail = None
	
	#  Insert new node at end position
	def insert(self, value) :
		#  Create a node
		node = LinkNode(value)
		if (self.head == None) :
			#  Add first node
			self.head = 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) :
		if (self.head == None) :
			print("Empty Linked List")
		else :
			print("\nLinked List Head to Tail ", end = " : ")
			#  Get first node of linked list
			temp = self.head
			#  iterate linked list 
			while (temp != None) :
				#  Display node value
				print("", temp.data, end = " ")
				#  Visit to next node
				temp = temp.next
			
			print("\nLinked List Tail to Head ", end = " : ")
			#  Get last node of linked list
			temp = self.tail
			#  iterate linked list 
			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
		temp = self.head
		#  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
				if (temp == self.head) :
					#  remove first node
					self.head = None
				
				counter -= 1
			
			if (self.tail != None) :
				self.tail.next = None
			
		else :
			print("Deleted ", n ," node are missing")
		
	

def main() :
	dll = DoublyLinkedList()
	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

Linked List Head to Tail  :  1  2  3
Linked List Tail to Head  :  3  2  1

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment