232.用栈实现队列
class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void push(int x) {
stack1.push(x);
}
public int pop() {
while (!stack1.empty()){
stack2.push(stack1.pop());
}
int a = stack2.pop();
while (!stack2.empty()){
stack1.push(stack2.pop());
}
return a;
}
public int peek() {
while (!stack1.empty()){
stack2.push(stack1.pop());
}
int a = stack2.peek();
while (!stack2.empty()){
stack1.push(stack2.pop());
}
return a;
}
public boolean empty() {
return stack1.empty();
}
}
这是一道模拟题,不涉及到具体算法,考察的就是对栈和队列的掌握程度。
使用栈来模式队列的行为,如果仅仅用一个栈,是一定不行的,所以需要两个栈一个输入栈,一个输出栈,这里要注意输入栈和输出栈的关系。
在push数据的时候,只要数据放进输入栈就好,但在pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。
225. 用队列实现栈
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.add(x);
}
public int pop() {
Queue<Integer> queue1 = new LinkedList<>();
int poped = 0;
while (!queue.isEmpty()){
poped = queue.poll();
if(!queue.isEmpty())
queue1.add(poped);
}
queue = queue1;
return poped;
}
public int top() {
Queue<Integer> queue1 = new LinkedList<>();
int poped = 0;
while (!queue.isEmpty()){
poped = queue.poll();
queue1.add(poped);
}
queue = queue1;
return poped;
}
public boolean empty() {
return queue.isEmpty();
}
}
依然想着用一个输入队列,一个输出队列,就可以模拟栈的功能,仔细想一下还真不行!
队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并没有变成先进后出的顺序。
所以用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质。
但是依然还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全用来备份的!