leet code 232. 利用栈实现队队列
问题描述
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
解题思路
思路就是用双个栈实现一个队列的出队顺序,重要在代码实现细节上
实现代码
import org.junit.Test;
import java.util.Stack;
/**
 * @author wz
 */
public class MyQueue {
    Stack<Integer> inStack = null;
    Stack<Integer> outStack = null;
    /*
    * 入列时直接在inStack中存储元素,
    * 当元素取出元素时 或 查看 队头元素时,如果 outStack 为空将inStack中的所有
    * 元素放到outStack中
    * */
    public MyQueue() {
        inStack = new Stack<>();
        outStack = new Stack<>();
    }
    public void push(int x) {
        inStack.push(x);
    }
    public int pop() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        }
        return outStack.pop();
    }
    public int peek() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        }
        return outStack.peek();
    }
    public boolean empty() {
        return outStack.isEmpty() && inStack.isEmpty();
    }
    public static void main(String[] args) {
        MyQueue myQueue = new MyQueue();
        myQueue.push(1);
        myQueue.push(2);
        myQueue.pop();
        myQueue.push(3);
        myQueue.push(4);
        System.out.println(myQueue.peek());
        System.out.println(myQueue.pop());
        System.out.println(myQueue.pop());
        System.out.println(myQueue.pop());
        System.out.println(myQueue.empty());
    }
}
实现细节
    在实现过程中要避免,inStack中的出栈的元素直接压到outStack中有元素的栈中,这种情况会使出队的顺序混乱,
现在 outStack 已有元素 1 2 3 4 , 出队 1 2 后将inStack中元素 5 压到 outStack中, outStack 中存储了 5 3 4,再出队一个元素得到的 5 ,此时出队顺序混乱。我们要保证outStack入栈时要保证outStack栈内元素为空。
    在设计时入队时直接将元素入栈到inStack中,当出队时和取出队首元素时,先判断outStack是否为空,如果outStack为空则将inStack中的所有元素入栈到outStack中。

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号