用栈实现队列 LeetCode 232
题目链接:[LeetCode 232 - 简单]
思路
栈具有后进先出,队列具有先进先出的功能,因此需要使用两个栈来模拟队列
使用栈实现队列:
class MyQueue {
Stack<Integer> stackIn;
Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);
}
public int pop() {
dumpstackIn();
return stackOut.pop();
}
public int peek() {
dumpstackIn();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
private void dumpstackIn(){
if(!stackOut.isEmpty())return;
while(!stackIn.isEmpty()){
stackOut.push(stackIn.pop());
}
}
}
总结
使用两个栈模拟队列,其中在pop()和peek()时需要将in栈里面的数据输入到out栈中
用队列实现栈 LeetCode 225
题目链接:[LeetCode 225 - 简单]
思路
使用队列来实现栈,主要是实现其后进先出的功能。
两个队列来实现栈:
class MyStack {
Queue<Integer> que1;
Queue<Integer> que2;
public MyStack() {
que1 = new LinkedList<>();
que2 = new LinkedList<>();
}
public void push(int x) {
que2.offer(x);
while(!que1.isEmpty()){
que2.offer(que1.poll());
}
Queue<Integer> queueTemp;
queueTemp = que1;
que1 = que2;
que2 = queueTemp;
}
public int pop() {
return que1.poll();
}
public int top() {
return que1.peek();
}
public boolean empty() {
return que1.isEmpty()&&que2.isEmpty();
}
}
总结
两个队列模拟栈,可以在输入时,调整好输出的顺序。 也可以通过一个队列来模拟栈。 一个队列来实现栈:
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
int size = queue.size();
while(size-- > 1){
queue.offer(queue.poll());
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}
①while(size-- > 1)为什么是大于1,因为刚刚输入的元素需要排在前面