当前位置:网站首页>[jzof] 09 realize queue with two stacks

[jzof] 09 realize queue with two stacks

2022-07-23 13:19:00 Sighed, angry

The idea is simple :

Using the first in first out rule simulation of stack to realize the first in first out of queue
1、 When inserting , Directly inserted into the stack1
2、 When it pops up , When stack2 Not empty , eject stack2 Top element of stack , If stack2 It's empty , take stack1 All the numbers in the stack are stacked one by one stack2, Then pop up stack2 Top element of stack .

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() {
    
        if (!stack2.isEmpty()) {
    
            return stack2.pop();
        } else{
    
            while (!stack1.isEmpty()) {
    
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}
原网站

版权声明
本文为[Sighed, angry]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230556026161.html