题目描述:
仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。
其中:
push:将元素 x 压入栈顶
pop:移除并返回栈顶元素
top:返回栈顶元素
empty:如果栈是空的,返回 true ;否则,返回 false
参考代码:
class MyStack {private Queue<Integer> queue1;private Queue<Integer> queue2;/** Initialize your data structure here. */public MyStack() {queue1 = new LinkedList<>();queue2 = new LinkedList<>();}/** Push element x onto stack. */public void push(int x) {if (!queue1.isEmpty()){queue1.offer(x);}else if (!queue2.isEmpty()){queue2.offer(x);}else {queue1.offer(x);}}/** Removes the element on top of the stack and returns that element. */public int pop() {if (empty()){return -1;}int qSize1 = queue1.size();int qSize2 = queue2.size();int data = 0;if (!queue1.isEmpty()){for (int i = 0; i < qSize1-1; i++) {queue2.offer(queue1.poll());}data = queue1.poll();}else {for (int i = 0; i < qSize2-1; i++) {queue1.offer(queue2.poll());}data = queue2.poll();}return data;}/** Get the top element. 拿到栈顶元素*/public int top() {if (empty()){return -1;}int qSize1 = queue1.size();int qSize2 = queue2.size();int data = 0;if (!queue1.isEmpty()){for (int i = 0; i < qSize1; i++) {data = queue1.poll();queue2.offer(data);}}else {for (int i = 0; i < qSize2; i++) {data = queue2.poll();queue1.offer(data);}}return data;}/** Returns whether the stack is empty. */public boolean empty() {if(queue1.isEmpty() && queue2.isEmpty()){return true;}return false;}
}
运行截图:
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态