算法作业_22(2017.5.18第十三周)

232. Implement Queue using Stacks

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
分析:用栈实现队列,就需要对两个栈进行操作,这里需要指定其中一个栈为存储元素的栈,假定为stack2,另一个为stack1。当有元素加入时,首先判断stack2是否为空(可以认为stack2是目标队列存放元素的实体),如果不为空,则需要将stack2中的元素全部放入(辅助栈)stack1中,这样stack1中存储的第一个元素为队尾元素;然后,将待加入队列的元素加入到stack1中,这样相当于实现了将入队的元素放入队尾;最后,将stack1中的元素全部放入stack2中,这样stack2的栈顶元素就变为队列第一个元素,对队列的pop和peek的操作就可以直接通过对stack2进行操作即可。

public class MyQueue {
    public Stack<Integer>  stack1 = new Stack<Integer>();
    public Stack<Integer>  stack2 = new Stack<Integer>();
    
    public void push(int x){
        while(!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
        stack1.push(x);
        while(!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
    }
    
    
    public int  pop(){
        return stack2.pop();
    }
    
    public int peek(){
        return stack2.peek();
    }
    
    public boolean empty(){
        return stack2.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();
 */
C++:
class MyQueue {
public:
    
   
    
    std::stack<int> stack1;
    std::stack<int> stack2;
    
    /** Push element x to the back of queue. */
    void push(int x) {
        while(!stack2.empty()){
            stack1.push(stack2.top());
            stack2.pop();
            
        }
        stack1.push(x);
        while(!stack1.empty()){
            stack2.push(stack1.top());
            stack1.pop();
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int res =  stack2.top();
        stack2.pop();
        return res;
    }
    
    /** Get the front element. */
    int peek() {
        return stack2.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        return stack2.empty();
    }
};

/**
 * 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();
 */


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章