05. Implement queue with two stacks

topic

Use two stacks to implement a queue to complete the Push and Pop operations of the queue. The elements in the queue are of type int.

Code

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();
    }
}
Published 12 original articles · praised 0 · visits 89

Guess you like

Origin blog.csdn.net/charlotte_tsui/article/details/105327586