算法作業_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();
 */


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