題目描述
用兩個棧來實現(xiàn)一個隊列叽赊,完成隊列的Push和Pop操作恋沃。 隊列中的元素為int類型。
改進前
import java.util.*;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
stack1.push(node);
}
public int pop() {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
改進后
import java.util.*;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
// 相對于改進前必指,stack1不需要將stack2中的元素倒騰過來了
stack1.push(node);
}
public int pop() {
// 相對于改進前囊咏,如果stack2中有值,則不需要從stack1中倒騰
if(stack2.isEmpty()) {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}