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

【剑指offer】 面试题9 用两个栈实现队列

2019-07-17 15:37 561 查看

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
牛客网:用两个栈实现队列

思路:
push时,push进的值都放在stack1;
pop时,当stack2为空时,我们把stack1中的元素逐个弹出并压入stack2。由于先进入队列的元素被压到stack1的底端,经过弹出和压入操作之后就处于stack2的顶端,可以直接弹出。当stack2不为空时,在stack2中的栈顶元素是最先进入队列的元素,可以直接弹出。

如何用两个队列实现一个栈?
push时,push值进非空queue;
pop时,将非空queue中的前面不需要pop的值dequeue,再依次进队到另一个queue。剩下queue中最后一个值pop。

C++代码:

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

int pop() {
int res;
if(!stack2.empty()){
res = stack2.top();
stack2.pop();
}
else {
while(!stack1.empty()){
int temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
res = stack2.top();
stack2.pop();
}
return res;
}

private:
stack<int> stack1;
stack<int> stack2;
};

JAVA代码:

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() {
int res;
if(!stack2.empty()){
res = stack2.peek();
stack2.pop();
}else{
while(!stack1.empty()){
int temp;
temp = stack1.peek();
stack1.pop();
stack2.push(temp);
}
res = stack2.peek();
stack2.pop();
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: