Implement Queue using Stacks
解题报告:这个就是考虑Queue 和 Stack的输入输出数据结构的不同, 我看LeetCode上还有大神直接用peek peek就完事了的, 我这个就是比较笨的方法。 首先确定要有两个stack存数据, 我是设定一个stack 存有所有的数据, 基本上这个stack 就是个queue 。 再回来考虑queue和stack 的区别, 在queue中先进先出, stack 先进后出。 所以我觉得push的时候是没什么区别的 都是按某种顺序放进这个数据结构里面。 区别就在pop的时候对它进行了处理, 其实我的stackTwo可以不设为全局也可以。 具体代码如下:
this question inspect the difference between Queue and Stack. They have different way to deal with input data and will see different output. In my solution, I use two stacks. One stores all data, this other one is used for operate pop() and peek(); here makes stack different. following is my code:
public class MyQueue {
StackstackOne = new Stack<>();
StackstackTwo = new Stack<>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
stackOne.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
while(!stackOne.empty()){
int element = stackOne.pop();
stackTwo.push(element);
}
int result = stackTwo.pop();
while(!stackTwo.empty()){
int elementTwo = stackTwo.pop();
stackOne.push(elementTwo);
}
return result;
}
/** Get the front element. */
public int peek() {
while(!stackOne.empty()){
int element = stackOne.pop();
stackTwo.push(element);
}
int result = stackTwo.peek();
while(!stackTwo.empty()){
int elementTwo = stackTwo.pop();
stackOne.push(elementTwo);
}
return result;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackOne.empty();
}
}