(java)用两个栈实现队列

题目:用两个栈实现一个队列,实现队列的两个函数appendTail和deleteHead,分别完成从队列的尾部增加节点,从头部删除节点。

 双栈模拟队列appendTail和deleteHead:

  • (1)abcd依次进入队列,我们将其存放在stack01中。
  • (2)我们需要将进行出队列操作,先进先出,则将stack01栈中的元素弹出到stack02栈中,之后a在stack02的栈顶出栈即可。
  • (3)我们需要将ef进队列,此时我们只需要将ef直接压入stack01栈中。
  • (4)我们再进行出队列操作,此时stack02不为空,直接出栈即可实现出队列操作。

分析:入队列操作只要直接将节点压入stack01中,而出队列分为两种情况,一是如果stack02为空,则stack01栈中的节点弹出到stack02中再进行出栈操作实现出队列,二是如果stack02不为空,则直接stack02弹出节点即为出队列操作。

代码实现如下:

package com.example.offer;

import java.util.Stack;
public class TestMyQueue {
    public static void main(String[] args) {
        MyQueue<String> myQueue=new MyQueue<>();
        myQueue.appendTail("我");
        myQueue.appendTail("爱");
        myQueue.appendTail("学习");
        myQueue.deleteHead();
        myQueue.deleteHead();
        myQueue.appendTail("爱");
        myQueue.appendTail("我");
        myQueue.printMyQueue();
    }
}
/**
 * 用两个栈实现队列
 */
class MyQueue <T>{
    private Stack<T> stack01=new Stack<>();
    private Stack<T> stack02=new Stack<>();

    //我们有两个栈可以利用,stack01用于进队列,stack02用于出队列
    /**
     * 从尾部增加元素
     * @param node
     */
    public void appendTail(T node){
        stack01.push(node);
    }
    /**
     * 从头部删除元素
     * @return
     */
    public T deleteHead(){
        if(stack02.isEmpty()&&!stack01.isEmpty()){
            while(!stack01.isEmpty()){
                stack02.push(stack01.pop());
            }
        }
        if(stack02.isEmpty()){
            return null;
        }
        return stack02.pop();
    }
    /**
     * 打印队列的值
     */
    public void printMyQueue(){
        if(stack01.isEmpty()&&stack02.isEmpty()){
            System.out.println("队列为空!");
        }
        //如果栈02存在元素则将栈02中的元素弹出
        while(!stack02.isEmpty()){
            System.out.println(stack02.pop());
        }
        //栈02是空的,将栈01的元素弹入栈02,再将栈02元素弹出
        if(stack02.isEmpty() && !stack01.isEmpty()){
            while(!stack01.isEmpty()){
                stack02.push(stack01.pop());
            }
            while(!stack02.isEmpty()){
                System.out.println(stack02.pop());
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值