用栈实现队列
思路
想要用栈实现队列的话 一个栈肯定是不够用的 我们可以用两个栈来进行操作(后进先出两次不就变成先进先出了么)
针对push操作:我们正常push进StackIn就可以
针对pop操作:如果stack-out为空 那么我们要先把stack-in中的元素pop出来然后赋值给stack-out 当stack-out不为空的时候 直接pop stack-out即可
针对peek操作:与pop大体操作类似 只不过最后对stack-out不是pop而是peek了
针对isEmpty操作:当stack-in和stack-out都为空时 返回true
代码
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() {
dumpstackIn();
return stackOut.pop();
}
/** Get the front element. */
public int peek() {
dumpstackIn();
return stackOut.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
// 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
private void dumpstackIn(){
if (!stackOut.isEmpty()) return;
while (!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
这里说一下当时我写代码出现的一个错误 在dumpstackIn这里:
for (int i = 0; i < stackIn.size(); i++){
stackOut.push(stackIn.pop());
}
我本意想的是把stackIn的元素给stackOut 利用stackIn的size 但是每次stackIn pop之后size是会发生变化的 因此要不就用while要不就提前用一个size把stackIn.size()进行存储
用队列实现栈
LinkedList实现了Queue接口 通常用offer()添加元素 pop()删除元素
思路
双队列
由于刚做完用栈实现队列 这题依然还想用两个队列来实现栈 只不过功能和上一个有所不同 我们不能通过两次先进先出达到后进先出的效果 但是我们可以把第二个队列当作一个备份的效果
针对push操作:我们正常push进queue1就可以
针对pop操作:我们想要的实际上就是queue1中的最后一个元素 那么我们可以遍历这个队列直到他只剩一个元素时 将该元素返回即可 并把前面遍历的元素加入queue2
针对top操作:与pop大体操作类似 只不过最后我们要把元素再加回queue2
针对isEmpty操作:当queue1和queue2都为空时 返回true
只使用一个队列
其实这道题目就是用一个队列就够了。
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
代码
//使用两个队列
class MyStack {
Queue<Integer> queue1 ;
Queue<Integer> queue2 ;
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
public void push(int x) {
queue1.offer(x);
}
public int pop() {
while (queue1.size()!=1){
queue2.offer(queue1.poll());
}
int result = queue1.poll();
//互换位置 因为queue1现在为空 queue2存放的是完整的队列
Queue<Integer> tmp = queue1;
queue1=queue2;
queue2=tmp;
return result;
}
public int top() {
while (queue1.size()!=1){
queue2.offer(queue1.poll());
}
int result = queue1.poll();
queue2.offer(result);
Queue<Integer> tmp = queue1;
queue1=queue2;
queue2=tmp;
return result;
}
public boolean empty() {
return queue1.isEmpty();
}
}
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
}
public int pop() {
int size = queue.size();
while (size != 1) { //保留最后一个元素
queue.offer(queue.poll());
size--;
}
return queue.poll();
}
public int top() {
int size = queue.size();
while (size != 1) {
queue.offer(queue.poll());
size--;
}
queue.offer(queue.peek());
return queue.poll();
}
public boolean empty() {
return queue.isEmpty();
}
}