LeetCode——Implement Queue using Stacks
Description:
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
Notes:
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
用栈来实现队列的功能。类似的还有用队列实现栈的功能。
思路:栈和队列对数据的处理是不同的。栈是先进后出(FILO)队列是先进先出(FIFO)。所以要用两个栈来维护一个队列。一个数据栈,一个暂存数据栈。数据栈用来存储数据,暂存数据栈用来把数据栈中的数据首尾交换,模拟队列的数据操作。
代码:
class MyQueue { Stack<Integer> stack1; Stack<Integer> stack2; public MyQueue() { stack1 = new Stack(); stack2 = new Stack(); } // Push element x to the back of queue. public void push(int x) { stack1.push(x); } // Removes the element from in front of queue. public void pop() { //把栈中的元素移到另一个栈中,首尾倒序。 while(!stack1.empty()) { stack2.push(stack1.pop()); } //移除堆首元素。 stack2.pop(); //还原数据队列。 while(!stack2.empty()) { stack1.push(stack2.pop()); } } // Get the front element. public int peek() { //把栈中的元素移到另一个栈中,首尾倒序。 while(!stack1.empty()) { stack2.push(stack1.pop()); } //获取堆首元素。 int front = stack2.peek(); //还原数据队列。 while(!stack2.empty()) { stack1.push(stack2.pop()); } return front; } // Return whether the queue is empty. public boolean empty() { return stack1.empty(); } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112835275-168981902.gif)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112841431-2047172832.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112847494-1544911856.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112904385-918783221.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111120143119-1302805212.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112856369-1466718103.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112830416-794416355.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111113919510-1155220901.gif)