使用隊列實現stack

兩個隊列實現一個stack

  1. q1只保持一個元素即可, 多餘的轉換到q2當中
  2. 出隊列元素,有兩種情況,
    • q1不爲空, 直接出隊列
    • 如果連續出隊列 q1可能爲空, 需要q2的部分元素放到q1當中去,

說白了就是元素搗鼓來搗鼓去的問題即可

class MyStack {

    /** Initialize your data structure here. */
    // 全部的數據逆轉即可
    Queue<Integer> q1;
    Queue<Integer> q2;
    public MyStack() {
        q1=new LinkedList<>();
        q2 =new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
       // 添加元素即可
        q1.offer(x);
        for(int i=0;i<q1.size()-1;i++){
            q2.offer(q1.poll());
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        top();
         return q1.poll();
    }
    
    /** Get the top element. */
    public int top() {
        // 確保元素裏面的
       if(q1.isEmpty()){
        //將q2當中的頂上部的元素搗鼓過來即可
           for(int i=0;i<q2.size()-1;i++){
               q2.offer(q2.poll());
           }
           
           q1.offer(q2.poll());
          
       } 
        return q1.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
       return q1.isEmpty()&& q2.isEmpty();
    }
}

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

核心事項
將一個筒裏面的元素搗鼓來搗鼓去

一個隊列實現一個stack

沒加入一個元素都是搗鼓搗鼓去就行,重置元素的基礎順序即可

兩個stack實現一個隊列

一個負責進入stack,另一個負責出stack,

只需要pop或者peek 元素的時候我們進行判斷out stack是否有元素即可,如果有沒有元素我們不斷得向裏面放入元素即可的情況

class MyQueue {

    /** Initialize your data structure here. */
    private Stack<Integer> in;
    private Stack<Integer> out;
    public MyQueue() {
        in =new Stack<>();
        out = new Stack<>();   
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
   // 只負責進入stack 即可
        in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
       peek();
      return  out.pop();  
    }
    
    /** Get the front element. */
    public int peek() {
        //如果in中有元素的情況
       //處理前面的元素,
        if(out.isEmpty()){
            while(!in.isEmpty()){
                out.push(in.pop());
            }
        }
     return   out.peek();
        
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty() && out.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();
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章