【LeetCode 225_数据结构_栈_实现】Implement Stack using Queues

本文详细介绍了栈数据结构的实现方式,并通过实例展示了如何使用栈解决实际问题,包括元素推入、弹出、获取顶部元素及判断栈是否为空的操作。

 1 class Stack {
 2 public:
 3     // Push element x onto stack.
 4     void push(int x) {
 5         int len = nums.size();
 6         nums.push(x);
 7         for (int i = 0; i < len; ++i) {
 8             nums.push(nums.front());
 9             nums.pop();
10         }
11     }
12 
13     // Removes the element on top of the stack.
14     void pop() {
15         nums.pop();
16     }
17 
18     // Get the top element.
19     int top() {
20         return nums.front();
21     }
22 
23     // Return whether the stack is empty.
24     bool empty() {
25         return nums.empty();
26     }
27 private:
28     queue<int> nums;
29 };

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值