Sword Finger Offer Interview Question 09. Use two stacks to implement the queue (queue, stack)

Title description

Implement a queue with two stacks. The declaration of the queue is as follows. Please implement its two functions appendTail and deleteHead to complete the functions of inserting integers at the end of the queue and deleting integers at the head of the queue. (If there are no elements in the queue, the deleteHead operation returns -1)
Insert picture description here

Ideas

See link for details

Code

class CQueue:
	def __init__(self):
		self.A, self.B = [], []
	def appendTail(self,value:int)->None:
		self.A.append(value)
	def deleteHead(self)->int:
		if self.B:
			return self.B.pop()
		if not self.A:
			return -1
		while self.A:
			self.B.append(self.A.pop())
		return self.B.pop()
Published 227 original articles · praised 633 · 30,000+ views

Guess you like

Origin blog.csdn.net/weixin_37763870/article/details/105500230