使用两个栈模拟队列,使用队列模拟栈

队列:一种先进先出的数据结构,FIFO
栈:一种后进先出的数据结构,FILO

1 使用两个栈模拟队里
栈是先进后出,1,2,3,4压栈,出栈为4,3,2,1,而队列是先进先出的,所以可以使用两个栈来模拟队列。

一个栈A模拟队列的入队操作,另一个栈B模拟出队,出队时将栈A全部出栈然后压入栈B。这里需注意当栈B为空时,才能进行A到B的转移,否则数据顺序会不一致。

private Stack<Integer> stackA = new Stack<>();
private Stack<Integer> stackB = new Stack<>();

public void enQueue(int element){
    
    
    stackA.push(element);
}

public Integer deQueue(){
    
    
    if (stackB.isEmpty()) {
    
    
        if (stackA.isEmpty()) {
    
    
            return null;
        }
        //栈B为空时,才进行A出栈B入栈操作
        while(!stackA.isEmpty()){
    
    
            stackB.push(stackA.pop());
        }
    }
    //栈B不为空时,直接出栈,保持原来顺序
    return stackB.pop();
}

2 使用队列模拟栈
队列是先进先出的,栈是后进先出,所以使用队列模拟栈,需要将队列中队尾元素之前的重新入队,每次都从队列里去除队尾元素即可。

private Queue<Integer> queue = new LinkedList<>();
private Integer tail = null;

public void push(int element){
    
    
    queue.offer(element);
    tail = element;
}

public Integer pop(){
    
    
    int size = queue.size();
    while(size>1){
    
    
        queue.add(queue.poll());
        size--;
    }
    tail = queue.peek();
    return queue.poll();
}

public Integer top(){
    
    
    return tail;
}

使用一个队列来模拟栈,入栈时直接向队列追加。出队时,元素个数大于1,就把前面的元素全部出队然后重新入队,使得队尾元素保持队首位置。使用一个单独属性,记录栈顶,也就是队尾。

猜你喜欢

转载自blog.csdn.net/weixin_43275277/article/details/108222804