剑指offer-面试题9-用两个栈实现队列&用两个队列实现栈

一:用两个栈实现队列

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop(){
        //如果stack2不为空,直接弹出栈顶元素,如果stack2为空,先将stack1元素推入stack2,再弹出
        if(stack2.isEmpty()){
            if(stack1.isEmpty())
                return -1;
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
            return stack2.pop();
        }else{
            return stack2.pop();
        }
    }
}

二:用两个队列实现栈

package offer;
import java.util.Queue;

import java.util.LinkedList;

public class offer_9 {
        
        Queue<Integer> queue1 = new LinkedList<>();
        Queue<Integer> queue2 = new LinkedList<>();
        
        public void push(int node){
                if(!queue1.isEmpty()) {
                        queue1.add(node);
                }else {
                        queue2.add(node);
                }       
        }
        
        public int pop(){
                if(queue1.isEmpty() && queue2.isEmpty()) {
                        return -1;
                }else {
                        if(queue1.isEmpty()) {
                                while(queue2.size()>1) {
                                        queue1.add(queue2.remove());
                                }
                                return queue2.remove();
                        }else{
                                while(queue1.size()>1) {
                                        queue2.add(queue1.remove());
                                }
                                return queue1.remove();
                        }
                }
        }
}

猜你喜欢

转载自blog.csdn.net/weixin_41993767/article/details/84671117