您的位置:首页 > 其它

使用两个栈实现队列

2016-03-02 19:24 295 查看
题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

思路:用两个栈来模拟队列,一个栈作为存储,另一个栈作为交换空间。队列的push操作就直接push到第一个栈中,队列的pop操作,需要取得第一个栈低的元素,所以先把第一个栈的元素出栈,入栈到第二个队列,那么取的元素就是第二个栈的栈顶,第二个栈直接出栈即可。然后把剩下的数据在还原回去。

实现代码:

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.push(node);
}

public int pop() {
while(!stack1.isEmpty()) {
stack2.push(stack1.pop());
}

int ret = stack2.pop();

while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}

return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: