您的位置:首页 > 职场人生

剑指Offer——面试题7:用两个栈实现队列

2017-05-02 16:09 183 查看


题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。


思路

当stack2中不为空时,在stack2中的栈顶元素是最先进入队列的元素,直接弹出。 如果stack2为空,把stack1中的元素逐个压入stack2.由于先进入队列的元素被压到stack1的低端,经过弹出和压入之后,就处于stack2的顶端,可以直接弹出。


实现

public class T07 {

Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
stack1.push(node);
}

public int pop() throws Exception {

if (!stack2.isEmpty()) {
return stack2.pop();
}

if (stack2.isEmpty()) {

if (stack1.isEmpty()) {
throw new Exception("queue is empty");
}

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

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