栈实现队列
创建两个栈来实现队列stackIn
和stackOut
用于输入
和输出
元素
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
push()
操作时,将元素push到stackIn中即可
pop()
和peek()
操作之前,都需要通过stackOutIsNull()
方法进行判断stackOut
这个栈中是否为空,若为空则需要将stackIn
栈中的元素全部push到stackOut
这个栈中;若不为空则直接返回,输出stackOut
中的元素
empty()
判断是否为空时直接判断是否同时满足stackIn
和stackOut
中都为空,都为空时才返回空
代码实现
import java.util.Stack;
class MyQueue {
Stack<Integer> stackIn = new Stack<>();
Stack<Integer> stackOut = new Stack<>();
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
stackOutIsNull();
return stackOut.pop();
}
public int peek() {
stackOutIsNull();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
public void stackOutIsNull(){
if(!stackOut.isEmpty()) return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
队列实现栈
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false
1.创建两个队列queue1和queue2,queue2备份queue1中的数据
2.每次需要栈顶元素的时候,就只留quque1中的队尾的那个元素,剩余的就存入queue2中
makeQueue1One()
方法就是使queue1中只有一个元素
3.每次操作完queue1后就需要将其还原,如果queue1中不为空,则将剩下的queue1中的元素放入queue2中,再将queue2中的元素全部放入queue1 中,等待下一次操作
agoQueue()
方法就是使queue2中的元素全部移入到queue1中
代码实现
import java.util.Queue;
class MyStack {
Queue <Integer> queue1 = new ArrayDeque<>();
Queue <Integer> queue2 = new ArrayDeque<>();
public MyStack() {
queue1 = new ArrayDeque<>();
queue2 = new ArrayDeque<>();
}
public void push(int x) {
queue1.add(x);
}
public int pop() {
makeQueue1One();
int result = queue1.poll();
agoQueue();
return result;
}
public int top() {
makeQueue1One();
int result = queue1.peek();
agoQueue();
return result;
}
public boolean empty() {
return queue1.isEmpty() && queue2.isEmpty();
}
public void makeQueue1One(){
int length = queue1.size();
if(length==1) return;
while(length!=1){
queue2.add(queue1.poll());
length--;
}
}
public void agoQueue(){
while(!queue1.isEmpty()){
queue2.add(queue1.poll());
}
while(!queue2.isEmpty()){
queue1.add(queue2.poll());
}
}
}