4

刷题1:用栈实现队列

 3 years ago
source link: https://segmentfault.com/a/1190000040232725
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

刷题1:用栈实现队列

发布于 27 分钟前

Leetcode链接:
232. 用栈实现队列

采用两个栈st和help,st用来入队,help用来出队。
1.val入队时,st.add(val)即可。
2.出队时,如果help为空,将st中的元素全部依次出栈,然后依次压入help栈中,接着help.pop()即可实现出队。如果help不为空,直接将help中剩下的元素出栈即可。出队的关键是根据栈help是否为空来做不同操作。

class MyQueue {
    Stack<Integer> st;
    Stack<Integer> help;
    /** Initialize your data structure here. */
    public MyQueue() {
        st = new Stack<Integer>();
        help = new Stack<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        st.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(empty()) return -1;
        //如果help为空,把st中元素全部压入help中再出队
        if(help.isEmpty()){
            while(!st.isEmpty()){
                help.push(st.pop());
            }
        }
        //如果help不为空,直接把栈顶弹出
        return help.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(empty()) return -1;
        if(help.isEmpty()){
            while(!st.isEmpty()){
                help.push(st.pop());
            }
        }
        return help.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        if(st.isEmpty() && help.isEmpty())
            return true;
        else
            return false;
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK