Skip to main content

Insert node at beginning of doubly linked list in python

Python program for Insert node at beginning of doubly linked list. Here problem description and explanation.

#  Python 3 Program For
#  insert new node at beginning of doubly linked list

#  Define class of linked list Node
class LinkNode :
	def __init__(self, data) :
		self.data = data
		self.next = None
		self.prev = None
	

class DoublyLinkedList :
	def __init__(self) :
		self.head = None
	
	#  Insert new node at beginning position
	def insert(self, value) :
		#  Create a node
		node = LinkNode(value)
		node.next = self.head
		#  When linked list is not empty
		if (self.head != None) :
			self.head.prev = node
		
		#  Make new head
		self.head = node
	
	#  Display node element of doubly linked list
	def display(self) :
		if (self.head == None) :
			print("Empty Linked List")
		else :
			print("  Doubly Linked List Element :")
			#  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
			
		
	

def main() :
	dll = DoublyLinkedList()
	#  Insert following linked list nodes
	dll.insert(70)
	dll.insert(60)
	dll.insert(50)
	dll.insert(40)
	dll.insert(30)
	dll.insert(20)
	dll.insert(10)
	#   NULL <- 10 <--> 20 <--> 30 <--> 40 <--> 50 <--> 60 <--> 70->NULL
	dll.display()

if __name__ == "__main__": main()

Output

  Doubly Linked List Element :
 10  20  30  40  50  60  70




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