用兩個隊列實現棧

核心思想

用兩個隊列來實現棧,因爲棧是後進先出的,而隊列是先進先出的,所以必須保持至少有一個空隊列,每次入棧的時候都要將入棧元素放到非空隊列隊尾,當然第一次都是空隊列,隨便選一個入隊就行,出棧時,將非空隊列裏面的元素依次出隊然後入隊到另一個空隊列中,只剩下一個元素作爲出棧元素,這樣就滿足了棧後進先出的特點。下面附上完整java代碼

import java.util.LinkedList;
import org.junit.Test;
public class StackByTwoQueue {
    private LinkedList<Integer> queue1=new LinkedList<Integer>();
    private LinkedList<Integer> queue2=new LinkedList<Integer>();

    public StackByTwoQueue() {
        super();
    }

    /**
     * 入棧
     * @param ele 要入棧的元素
     */
    private void push(Integer ele){//入棧時兩個隊列至少有一個是空隊列
        if(isEmpty()){//如果兩個隊列全是空的,則必須要選擇一個隊列加入新元素
            queue1.add(ele);
            return;//提前結束,避免過多的比較
        }
        //只在非空隊列加入新元素
        if(!queue1.isEmpty()){
            queue1.add(ele);
            return;//避免多餘的比較,提前結束
        }
        //只在非空隊列加入新元素
        if(!queue2.isEmpty()){
            queue2.add(ele);
        }
    }

    private boolean isEmpty(){
        if(queue1.isEmpty() && queue2.isEmpty()){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 出棧
     * @return 棧頂元素
     */
    private Integer pop(){
        if(isEmpty()){
            try {
                throw new Exception("棧空");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        if(queue1.isEmpty()){//將非空隊列裏面的元素依次出隊,最後只剩下一個作爲出棧元素
            while(queue2.size()>1){
                queue1.add(queue2.poll());
            }
            return queue2.poll();
        }

        if(queue2.isEmpty()){//將非空隊列裏面的元素依次出隊,最後只剩下一個作爲出棧元素
            while(queue1.size()>1){
                queue2.add(queue1.poll());
            }
            return queue1.poll();
        }
        return null;
    }

    @Test
    public void testStackByTwoQueue(){
        StackByTwoQueue stack=new StackByTwoQueue();
        for (int i =0; i <4; i++) {
            stack.push(i);
        }

        while(!stack.isEmpty()){
            System.out.print(stack.pop()+" ");
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章