栈实现队列——LeetCode第232题
讲个笑话:哎!我遇到的99%的问题都可以用钱解决,剩下的1%,需要用更多的钱。“唉?你们四川人谈恋爱怎么叫耍朋友啊!!耍字多不好啊!” 四川女孩回答:“那你们谈恋爱还叫搞对象呢。搞字就好听呦?”
力扣题目描述
示例:
读懂题意
首先第一点我们得明白栈和队列的区别,栈是先进后出,队列是先进先出。且对栈的操作都是栈的尾部,而队列呢?增添是在尾部而出列在列的头部,所以两者的区别还是挺大的,那么怎样来实现呢?题目告诉我们需要利用两个栈来实现,队列的操作有入列 、出列、 查找列首元素和判断是否为空的方法。
两个栈实现队列的示意图
第一个栈A 让元素1、2、3入栈
元素1、2、3入栈
如果要出列的话,就是获取元素1,此时栈A弹栈直到取到栈底元素,将弹出的元素入栈到栈B(pop()方法)
如果此时有新的元素要入栈时,先将栈B的元素弹栈到栈A中最后将新元素入栈到栈A中。(push())
而peek()方法相当于和出列类似,只是此时栈A不谈栈,而判断是否为空可以定义一个记录有效长度的size,push一次size加一,pop一次size减一。最后为空只需看size是否为0.
代码
class MyQueue {
Stack<Integer> one ;
Stack<Integer> two ;
/** Initialize your data structure here. */
public MyQueue() {
one = new Stack();
two =new Stack();
}
/** Push element x to the back of queue. */
public void push(int x) {
one.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
while(!one.isEmpty()){
two.push(one.pop());
}
int value = two.pop();
while(!two.isEmpty()){
one.push(two.pop());
}
return value;
}
/** Get the front element. */
public int peek() {
while(!one.isEmpty()){
two.push(one.pop());
}
int value = two.peek();
while(!two.isEmpty()){
one.push(two.pop());
}
return value;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return one.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
package com.heng.动态数组;
//栈实现队列
public class StackToQueue {
public static void main(String[] args) {
QueueImplByStack<Integer> queue = new QueueImplByStack<>();
for (int i = 1; i <= 3; i++) {
queue.offer(i);
}
System.out.println(queue);
System.out.println(queue.poll());
queue.offer(4);
System.out.println(queue);
}
}
class QueueImplByStack<E> {
private ArrayStack<E> stackA;
private ArrayStack<E> stackB;
public QueueImplByStack () {
stackA = new ArrayStack<>();
stackB = new ArrayStack<>();
}
public void offer(E element) {
stackA.push(element);
}
public E poll() {
while (!stackA.isEmpty()) {
stackB.push(stackA.pop());
}
E ret = stackB.pop();
while (!stackB.isEmpty()) {
stackA.push(stackB.pop());
}
return ret;
}
public E element() {
while (!stackA.isEmpty()) {
stackB.push(stackA.pop());
}
E ret = stackB.peek();
while (!stackB.isEmpty()) {
stackA.push(stackB.pop());
}
return ret;
}
@Override
public String toString() {
return stackA.toString();
}
}
总结
其实我们只需要明白栈实现队列的一个过程,便会很好理解栈是如何实现队列的!