题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思想描述:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.add(node);
\\add(E e) 和 E push(E e)区别在于返回值的不同
}
public int pop() {
if(stack2.empty()){
\\若stack2中有元素的话,要让stack2中的元素出栈
while(!stack1.empty()){
\\将stack1中的元素全部压入stack2
stack2.add(stack1.pop());
}
}
int t = stack2.pop();
\\pop()和peek()的区别在于
pop():返回栈顶元素并将使该元素出栈
peek():只是返回栈顶元素
return t;
}
}