implement queue using linked list in python

Python program for implement queue using linked list. Here problem description and explanation.

#  Python 3 Program for
#  Implement queue using linked list

#  Create Q node
class QNode :
	def __init__(self, value) :
		self.data = value
		self.next = None
	

class MyQueue :
	def __init__(self) :
		self.head = None
		self.tail = None
		self.count = 0
	
	def size(self) :
		return self.count
	
	def isEmpty(self) :
		return self.count == 0
	
	#  Add new node of queue
	def enqueue(self, value) :
		#  Create a new node
		node = QNode(value)
		if (self.head == None) :
			#  Add first element into queue
			self.head = node
		else :
			#  Add node at the end using tail 
			self.tail.next = node
		
		self.count += 1
		self.tail = node
	
	#  Delete a element into queue
	def dequeue(self) :
		if (self.head == None) :
			print("Empty Queue")
			return -1
		
		#  Pointer variable which are storing 
		#  the address of deleted node
		temp = self.head
		#  Visit next node 
		self.head = self.head.next
		self.count -= 1
		if (self.head == None) :
			#  When deleting a last node of linked list
			self.tail = None
		
		return temp.data
	
	#  Get front node
	def peek(self) :
		if (self.head == None) :
			print("Empty Queue")
			return -1
		
		return self.head.data
	

def main() :
	task = MyQueue()
	#  Initially number of element
	print("isEmpty : ", task.isEmpty())
	#  Add element into queue
	task.enqueue(10)
	task.enqueue(20)
	task.enqueue(30)
	task.enqueue(40)
	task.enqueue(50)
	#  Test other function
	print("size : ", task.size())
	print("peek : ", task.peek())
	print("dequeue : ", task.dequeue())
	print("size : ", task.size())
	print("peek : ", task.peek())
	print("isEmpty : ", task.isEmpty())

if __name__ == "__main__": main()

Output

isEmpty :  True
size :  5
peek :  10
dequeue :  10
size :  4
peek :  20
isEmpty :  False


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







© 2021, kalkicode.com, All rights reserved