算法-栈和队列的相互转换


由于两种方法都很简单,这里就不多说了

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();
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_23594799/article/details/105493243