题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路:
java队列和栈的使用
队列的特点:
先进入的元素先出来,后进入的元素后出来。
栈的特点:
先进入的元素后出来,后进入的元素先出来。
1.利用stack1来存储元素。
2.不断的将stack1出栈的元素压入stack2的顶部。
3.stack2的元素出栈。
总结:利用两个栈来改变元素的序列。实现队列的顺序
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
//stack1入栈
stack1.push(node);
}
public int pop() {
while (!stack2.isEmpty()) {
//stack2出栈
return stack2.pop();
}
while (!stack1.isEmpty()) {
//stack2入栈的元素为stack1的出栈元素
stack2.push(stack1.pop());
}
//return
return stack2.pop();
}