栈实现队列
问题
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty)
问题分析
使用两个栈,一个栈用于输入,另一用于输出。
具体操作
- 在入队(push)时,直接将数据放入输入栈
- 在出队(pop)时,如果输出栈为空,就将输入栈的数据全部弹出并压入输出栈,再从输出栈弹出数据,如果输出栈不为空则直接弹出数据
- 返回队首元素(peek)时,和出队的操作是一样的,只不过最后不是弹出元素,是返回输出栈的栈顶元素
- 判断队列是否为空(empty),当两个栈都为空时则为空
代码
class MyQueue {
Stack<Integer> stackIn; //输入栈
Stack<Integer> stackOut; //输出栈
/** Initialize your data structure here. */
public MyQueue() {
stackIn=new Stack();
stackOut=new Stack();
}
/** Push element x to the back of queue. */
//入队,将数据压入输入栈
public void push(int x) {
stackIn.push(x);
}
/** Removes the element from in front of queue and returns that element. */
//出队
public int pop() {
//输出栈为空
if(stackOut.isEmpty()){
//将输入栈的数据全部弹出,压入输入出栈
while (!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
//从输出栈弹出数据
return stackOut.pop();
}
/** Get the front element. */
//返回队首元素
public int peek() {
//输出栈为空
if(stackOut.isEmpty()){
//将输入栈的数据全部弹出,压入输入出栈
while (!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
//取出输出栈的栈顶元素
return stackOut.peek();
}
/** Returns whether the queue is empty. */
//判断队列是否为空
public boolean empty() {
return stackOut.isEmpty() && stackIn.isEmpty();
}
}
队列实现栈
问题
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。
问题分析
采用两队列,queue1和queue2,queue1完成实际的栈操作,queue2作为辅助队列协助queue1实现栈的操作
-
在压栈(push)时,结合queue1和queue2,让每次压入栈的元素放在queue1的队首
- 队列中无元素,queue1为空,元素进入queue2,然后将对queue1和queue2内容进行交换
- 队列中有元素,queue1 不为空,元素进入queue2,然后将queue1中的元素全部出队,并依次进入queue2,然后将对queue1和queue2内容进行交换
-
在压栈操作时,queue1实现了压栈元素放入队首,所以top、pop 和 empty直接使用queue1的相应操作就行
代码
class MyStack {
//队列1,实现栈操作的队列
Queue<Integer> queue1;
//队列2,用于保存数据、对数据进行交换的队列
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) {
//元素进入队列2
queue2.offer(x);
//队列1所有元素出队,并进入队列2
while (!queue1.isEmpty()) {
queue2.offer(queue1.poll());
}
//将队列1和队列2互换
Queue<Integer> temp = queue1;
queue1 = queue2;
queue2 = temp;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
return queue1.poll();
}
/** Get the top element. */
public int top() {
return queue1.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}