LeetCode 232. Implement Queue using Stacks

题目

class MyQueue {
public:
    int stack[100005];
    int stack2[100005];
    int pos;
    int pos2;
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        stack[pos++]=x;
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        
        while(pos!=0)
        {
            stack2[pos2++]=stack[pos-1];
            pos--;
        }
        int x= stack2[pos2-1];
        pos2--;
        
        while(pos2!=0)
        {
            stack[pos++]=stack2[pos2-1];
            pos2--;
        }
        return x;
        
    }
    
    /** Get the front element. */
    int peek() {

        while(pos!=0)
        {
            stack2[pos2++]=stack[pos-1];
            pos--;
        }
        int x=stack2[pos2-1];
        
        while(pos2!=0)
        {
            stack[pos++]=stack2[pos2-1];
            pos2--;
        }
        return x;
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        
      return pos==0;
        
    }
};

/**
 * 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();
 * bool param_4 = obj->empty();
 */
posted @ 2020-03-04 15:27  Shendu.CC  阅读(73)  评论(0编辑  收藏  举报