如何使用栈来实现队列结构?

堆栈和队列两种最基本的数据结构,相信大部分同学都不陌生,但是你知道如何在不使用编程语言自带的数据结构的情况下,实现自己的队列结构吗?

今天就带大家来学习一个最简单的使用两个栈来实现队列结构。

设要实现的队列为 q,用于实现 q 的堆栈为 stack1 和 stack2。q 可以通过两种方式实现: 

方法 1(该方法enqueue的复杂度较高):该方法确保最早进入的元素始终位于 stack1 的顶部,因此 dequeue 操作只是从 stack1 中弹出元素。要将元素放在 stack1 的顶部,我们需要使用 stack2。

enqueue(x): 

  • 当 stack1 不为空时,将 stack1 中的所有内容push到 stack2。
  • 将 x push到 stack1(假设堆栈的大小是无限的)。
  • 最后将所有元素再推回stack1。
  • 这里的时间复杂度为O(n)

dequeue():

  • 如果 stack1 为空,则队列为空
  • 否则从 stack1 中弹出一个元素并返回
  • 这里的时间复杂度为O(1)

下面是上述方法的实现:

class Queue:
	def __init__(self):
		self.s1 = []
		self.s2 = []

	def enQueue(self, x):
		
		# Move all elements from s1 to s2
		while len(self.s1) != 0:
			self.s2.append(self.s1[-1])
			self.s1.pop()

		# Push item into self.s1
		self.s1.append(x)

		# Push everything back to s1
		while len(self.s2) != 0:
			self.s1.append(self.s2[-1])
			self.s2.pop()

	# Dequeue an item from the queue
	def deQueue(self):
		
			# if first stack is empty
		if len(self.s1) == 0:
			print("Q is Empty")
	
		# Return top of self.s1
		x = self.s1[-1]
		self.s1.pop()
		return x

if __name__ == '__main__':
	q = Queue()
	q.enQueue(1)
	q.enQueue(2)
	q.enQueue(3)

	print(q.deQueue())
	print(q.deQueue())
	print(q.deQueue())

方法 2(该方法dequeue的复杂度较高):在该方法中,enqueue操作,新元素进入stack1的顶部。dequeue操作中,如果 stack2 为空,则将所有元素移动到 stack2,最后返回 stack2 的顶部元素。  

enqueue(x):

  • 将x添加到stack1中(假设stack1的大小为无穷)
  • 这里的时间复杂度为O(1)

dequeue():

  • 如果两个队列都为空,则队列为空
  • 如果stack2为空,当 stack1 不为空时,将 stack1 中的所有内容推送到 stack2。
  • 从stack2中弹出元素并返回
  • 这里的时间复杂度为O(n)

方法 1 在 enQueue 操作中移动所有元素两次,而方法 2(在 deQueue 操作中)移动元素一次,并且只有在 stack2 为空时才移动元素。因此,dequeue操作的摊销复杂度为O(1),因此方法2优于方法1.

下面是方法2的实现

class Queue:
	def __init__(self):
		self.s1 = []
		self.s2 = []

	# EnQueue item to the queue
	def enQueue(self, x):
		self.s1.append(x)

	# DeQueue item from the queue
	def deQueue(self):

		# if both the stacks are empty
		if len(self.s1) == 0 and len(self.s2) == 0:
			print("Q is Empty")
			return

		# if s2 is empty and s1 has elements
		elif len(self.s2) == 0 and len(self.s1) > 0:
			while len(self.s1):
				temp = self.s1.pop()
				self.s2.append(temp)
			return self.s2.pop()

		else:
			return self.s2.pop()

	# Driver code
if __name__ == '__main__':
	q = Queue()
	q.enQueue(1)
	q.enQueue(2)
	q.enQueue(3)

	print(q.deQueue())
	print(q.deQueue())
	print(q.deQueue())

看到这里你学会了吗?

其他语言代码下载链接:

(包含各种语言:C、Python、Java、C++、C#等)

免费​资源下载:Queue with two Stacks

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值