232. Implement Queue using Stacks
两个栈做法,注意peek和pop方法。考虑两种情况,
push(1), push(2), push(3), peek() :一次性在s1中push
1,2,3
,再pop(), 要把s1中的元素转移到s2中去。push(1), push(2) ,peek(), push(3), peek():如果peek转移了,那么s2中情况为
3,1,2
,第二次调用peek就会得到3,所以调用peek时必须满足s2为空的条件。
根据情况一可以写出while循环,s1->s2转移元素。
while (!s1.isEmpty()) {
s2.push(elemnts from s1);
}
根据情况二给while循环加上限制条件, s1->s2时,s2必须为空。
if (s2.isEmpty()) {
while () {...}
}
class MyQueue {
LinkedList<Integer> s1;
LinkedList<Integer> s2;
/** Initialize your data structure here. */
public MyQueue() {
this.s1 = new LinkedList<>();
this.s2 = new LinkedList<>();
}
/** Push element x to the back of queue. */
public void push(int x) {
this.s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
peek();
return this.s2.pop();
}
/** Get the front element. */
public int peek() {
if (this.s2.isEmpty()) {
while (!this.s1.isEmpty()) {
this.s2.push(this.s1.pop()); // transfer elements to l2
}
}
return this.s2.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.isEmpty() && s2.isEmpty();
}
}