云计算百科
云计算领域专业知识百科平台

用栈实现队列

题目链接

链接: 用栈实现队列

题目要求

在这里插入图片描述

解题思路

在这里插入图片描述

代码实现

public class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;

public MyQueue() {
this.stack1 = new Stack<>();
this.stack2 = new Stack<>();
}

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

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

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

public boolean empty() {
return stack1.isEmpty() && stack2.isEmpty();
}
}

赞(0)
未经允许不得转载:网硕互联帮助中心 » 用栈实现队列
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!