Question

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 must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
    • 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.
    • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Solution

Java Queue Interface

Key to the solution is to use two queues. Queue is strictly First In, First Out.

Two Methods

Method 1: making push operation costly

push(s, x) // x is the element to be pushed and s is stack
1) Enqueue x to q2
2) One by one dequeue everything from q1 and enqueue to q2.
3) Swap the names of q1 and q2
// Swapping of names is done to avoid one more movement of all elements
// from q2 to q1. pop(s)
1) Dequeue an item from q1 and return it.

Method 2: making pop operation costly

push(s,  x)
1) Enqueue x to q1 (assuming size of q1 is unlimited). pop(s)
1) One by one dequeue everything except the last element from q1 and enqueue to q2.
2) Dequeue the last item of q1, the dequeued item is result, store it.
3) Swap the names of q1 and q2
4) Return the item stored in step 2.
// Swapping of names is done to avoid one more movement of all elements
// from q2 to q1.
 class MyStack {
Queue<Integer> queue1;
Queue<Integer> queue2; public MyStack(){
queue1 = new LinkedList<Integer>();
queue2 = new LinkedList<Integer>();
} // Push element x onto stack.
public void push(int x) {
queue1.add(x);
} // Removes the element on top of the stack.
public void pop() {
if (queue1.peek() == null)
return;
int length = queue1.size();
queue2 = new LinkedList<Integer>();
while (length > 1) {
queue2.add(queue1.remove());
length--;
}
queue1 = queue2;
} // Get the top element.
public int top() {
if (queue1.peek() == null)
return -1;
queue2 = new LinkedList<Integer>();
int length = queue1.size();
int lastElement = 0;
while (length > 0) {
lastElement = queue1.remove();
queue2.add(lastElement);
length--;
}
queue1 = queue2;
return lastElement;
} // Return whether the stack is empty.
public boolean empty() {
if (queue1.peek() == null)
return true;
return false;
}
}

Implement Stack using Queues 解答的更多相关文章

  1. leetcode:Implement Stack using Queues 与 Implement Queue using Stacks

    一.Implement Stack using Queues Implement the following operations of a stack using queues. push(x) - ...

  2. 【LeetCode】232 & 225 - Implement Queue using Stacks & Implement Stack using Queues

    232 - Implement Queue using Stacks Implement the following operations of a queue using stacks. push( ...

  3. 232. Implement Queue using Stacks,225. Implement Stack using Queues

    232. Implement Queue using Stacks Total Accepted: 27024 Total Submissions: 79793 Difficulty: Easy Im ...

  4. leetcode 155. Min Stack 、232. Implement Queue using Stacks 、225. Implement Stack using Queues

    155. Min Stack class MinStack { public: /** initialize your data structure here. */ MinStack() { } v ...

  5. Implement Queue by Two Stacks & Implement Stack using Queues

    Implement Queue by Two Stacks Implement the following operations of a queue using stacks. push(x) -- ...

  6. [LeetCode] Implement Stack using Queues 用队列来实现栈

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  7. Java for LeetCode 225 Implement Stack using Queues

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  8. Implement Stack using Queues

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  9. (leetcode)Implement Stack using Queues

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

随机推荐

  1. C# 调用外部程序,并获取输出和错误信息

    1. 同步模式 public void exec(string exePath, string parameters) { System.Diagnostics.ProcessStartInfo ps ...

  2. SQLite-CONSTRAINTS(约束)

    SQLite – CONSTRAINTS(约束) 约束是数据列在表上执行的规则.这些是用来限制的数据类型可以进入一个表.这样可以确保数据的准确性和可靠性在数据库中. 级或表级约束可以列.列级约束是仅适 ...

  3. csdn博客被一个无名网站套用,不知大家是否也是这样?

    今天闲来无事,用google搜索了一下自己csdn的博客名,查看了一下搜索结果,发现自己在csdn上的博客被其他一下网站转载了,转载后注明作者的网站这里我也就不去说了,问题是我发现了一个名叫“开心问答 ...

  4. mysql用户和权限管理

    用户和权限管理 Information about account privileges is stored in the user, db, host, tables_priv, columns_p ...

  5. 【转】Android中自动连接到指定SSID的Wi-Fi

    最近在做一个项目,其中涉及到一块“自动连接已存在的wifi热点”的功能,在网上查阅了大量资料,五花八门,但其中一些说的很简单,即不能实现傻瓜式的拿来就用,有些说的很详细,但其中不乏些许错误造成功能无法 ...

  6. 玩程序 之 一 . 字符串处理工具(可通过C#脚本扩展)

    平常喜欢写点小东西玩玩,既可以娱乐自己满足自己的虚荣心,又可以方便工作和学习,今天且拿出一个来,与大家一起分享!  1. 软件介绍 言归正传,先看看需求,有这样一串字符串 abc,def,ghi,jk ...

  7. jqGrid源代码分析(一)

    废话少说.先上grid.base.js 整体结构图 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc3B5MTk4ODEyMDE=/font/5a6L5L2 ...

  8. codevs1009

    题目地址:http://codevs.cn/problem/1009/ 分析: [TAG]FLOYD,乘法原理,高精度 [构思] 求可变换数的个数,那么就是组合数学的内容,四个原理的应用: 假如能知道 ...

  9. 概率dp ZOJ 3640

    Help Me Escape Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu Submit ...

  10. a标签伪类的顺序

    在一次开发项目中,我用a链接来做效果,测试的时候发现,a:hover被点击后的效果就不再了!我百度才知道,原来在css写a链接也是有顺序之分的. 顺序应该是: a:link a标签还未被访问的状态: ...