05.用两个栈实现队列

题目

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

代码实现

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() {
    	//需要注意判断条件
    	//1.当stack2为空的时候,将stack1中的元素依次添加到stack2中 	
        if(stack2.size() <= 0){
            while(stack1.size() != 0){
                stack2.push(stack1.pop());
            }
        }
        //2.当stack2为不为空的时候,直接将stack2中的元素出栈
        return stack2.pop();
    }
}
发布了12 篇原创文章 · 获赞 0 · 访问量 89

猜你喜欢

转载自blog.csdn.net/charlotte_tsui/article/details/105327586