美文网首页
[刷题防痴呆] 0225 - 用队列实现栈 (Implement

[刷题防痴呆] 0225 - 用队列实现栈 (Implement

作者: 西出玉门东望长安 | 来源:发表于2022-03-13 00:00 被阅读0次

题目地址

https://leetcode.com/problems/implement-stack-using-queues/

题目描述

225. Implement Stack using Queues

Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push, top, pop, and empty).

Implement the MyStack class:

void push(int x) Pushes element x to the top of the stack.
int pop() Removes the element on the top of the stack and returns it.
int top() Returns the element on the top of the stack.
boolean empty() Returns true if the stack is empty, false otherwise.
Notes:

You must use only standard operations of a queue, which means only push to back, peek/pop from front, size, and is empty operations are valid.
Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue), as long as you use only a queue's standard operations.
 

Example 1:

Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]

Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

思路

  • 用两个queue来实现.
  • 增加swapQueues方法和moveItems方法.
  • pop的时候, 先把queue1的元素move到queue2里. 只剩一个在queue1中, 出队列, 然后swapQueues.

关键点

代码

  • 语言支持:Java
class MyStack {

    /** Initialize your data structure here. */
    
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;
    
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue1.offer(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        moveItems();
        int item = queue1.poll();
        swapQueues();
        return item;
    }
    
    /** Get the top element. */
    public int top() {
        moveItems();
        int item = queue1.poll();
        swapQueues();
        queue1.offer(item);
        return item;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue1.isEmpty();
    }
    
    private void moveItems() {
        while (queue1.size() != 1) {
            queue2.offer(queue1.poll());
        }
    }
    
    private void swapQueues() {
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

相关文章

网友评论

      本文标题:[刷题防痴呆] 0225 - 用队列实现栈 (Implement

      本文链接:https://www.haomeiwen.com/subject/iuhkdrtx.html