【LeetCode 232_数据结构_队列_实现】Implement Queue using Stacks

本文详细阐述了一种高效队列实现方式,通过利用辅助栈结构,在不改变基本队列操作的同时,显著提高了队列的弹性和性能。该实现不仅支持常规的入队和出队操作,还提供了队首元素的预览功能,并且确保了队列操作的效率不受队列内部数据变化的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 class Queue {
 2 public:
 3     // Push element x to the back of queue.
 4     void push(int x) {
 5         while (!nums.empty()) {
 6             nums_assist.push(nums.top());
 7             nums.pop();
 8         }
 9         nums.push(x);
10         while (!nums_assist.empty()) {
11             nums.push(nums_assist.top());
12             nums_assist.pop();
13         }
14     }
15 
16     // Removes the element from in front of queue.
17     void pop(void) {
18         nums.pop();
19     }
20 
21     // Get the front element.
22     int peek(void) {
23         return nums.top();
24     }
25 
26     // Return whether the queue is empty.
27     bool empty(void) {
28         return nums.empty();
29     }
30 private:
31     stack<int> nums, nums_assist;
32 };

 

转载于:https://www.cnblogs.com/mengwang024/p/4630138.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值