博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Implement Stack using Queues
阅读量:7050 次
发布时间:2019-06-28

本文共 1650 字,大约阅读时间需要 5 分钟。

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Notes:

  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue -- which means only push to backpop from frontsize, and is empty operations are valid.

Credits:

Special thanks to  for adding this problem and all test cases.

水题。用两个队列来模拟。

1 class Stack { 2 private: 3     queue
que[2]; 4 int cur = 0; 5 6 public: 7 // Push element x onto stack. 8 void push(int x) { 9 que[cur].push(x);10 }11 12 // Removes the element on top of the stack.13 void pop(void) {14 while (que[cur].size() > 1) {15 que[1 - cur].push(que[cur].front());16 que[cur].pop();17 }18 que[cur].pop();19 cur = 1 - cur;20 }21 22 // Get the top element.23 int top(void) {24 while (que[cur].size() > 1) {25 que[1 - cur].push(que[cur].front());26 que[cur].pop();27 }28 int top = que[cur].front();29 que[1 - cur].push(que[cur].front());30 que[cur].pop();31 cur = 1 - cur;32 return top;33 }34 35 // Return whether the stack is empty.36 bool empty(void) {37 return que[cur].empty();38 }39 };

 

转载地址:http://bnpol.baihongyu.com/

你可能感兴趣的文章
MarkLight
查看>>
显示/隐藏Mac下的隐藏文件
查看>>
关于数字签名简要原理
查看>>
POJ-3565 Ants 空间点对不相交匹配-最小权值匹配
查看>>
第三次月考
查看>>
单例模式的理解与应用
查看>>
springmvc(一)
查看>>
Hibernate与 MyBatis的比较
查看>>
【51NOD-0】1137 矩阵乘法
查看>>
Android使用静默安装时碰见的问题
查看>>
MySQL单机多实例安装并配置主从复制
查看>>
awk调用shell命令的两种方法:system与print
查看>>
网络对抗技术 20164320 王浩 Exp 9 Web安全基础
查看>>
谷歌开源第二代机器学习系统 TensorFlow
查看>>
juqery模板 Templates
查看>>
eclipse 自动创建web.xml
查看>>
python 基础回顾2
查看>>
Servlet 示例
查看>>
十一.单表更新及多表更新
查看>>
深入理解DOM节点类型第三篇——注释节点和文档类型节点
查看>>