算法-棧和隊列的相互轉換


由於兩種方法都很簡單,這裏就不多說了

1、兩個棧實現一個隊列

     class MyQueue{
        private Stack<Integer> input;
        private Stack<Integer> output;

        public MyQueue() {
            input =new Stack<>();
            output = new Stack<>();
        }

        public void offer(int val){
            input.push(val);
        }
        public int poll(){
            if(isEmpty()){
                throw new IndexOutOfBoundsException();
            }
            if(output.size()==0){
                while (input.isEmpty()==false){
                    output.push(input.pop());
                }
            }
            return output.pop();
        }
        public boolean isEmpty(){
            return input.isEmpty()&&output.isEmpty();
        }

    }

2、隊列實現棧

    class MyStack{
        private Queue<Integer> queue;
        private int count=0;
        public MyStack() {
            queue=new LinkedList<>();
        }

        public void offer(int val){
            queue.offer(val);
            for (int i=0;i<count;i++){
                queue.offer(queue.poll());//隊列頭插到隊列尾,隊尾便隊頭
            }
            count++;
        }
        public int poll(){
            if(isEmpty()){
                throw new IndexOutOfBoundsException();
            }
            count--;
            return queue.poll();
        }
        public boolean isEmpty(){
            return queue.isEmpty();
        }
    }

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