题9:栈和队列的相互表示

题9:
用两个队列表示栈
用两个栈表示队列

两个队列表示栈:

  1. 准备两个队列queue和help
  2. 进栈操作:将所有的值放入queue队列
  3. 出栈操作:
    1. 将queue队列最后一个数之前的数取出放到help队列中
    2. 取出最后一个数对外返回
    3. 交换两个队列的指针引用
public class QueueToStack{

 	//用两个队列表示栈
    private Queue<Integer> queue;
    private Queue<Integer> help;

    public TwoQueueToStack(){
        queue = new LinkedList<Integer>();
        help = new LinkedList<Integer>();
    }

    //进栈
    public void push(int pushInt){
        queue.add(pushInt);
    }

    //出栈    把queue最后一个数之前的数pop到help队列里  把queue队列的最后一个数pop出返回,交换两个队列的引用
    public int poll(){
        if(queue.isEmpty()){
            throw new RuntimeException("The Stack Is Empty!");
        }
        while(queue.size() > 1){
            help.add(queue.poll());
        }
        int res = queue.poll();
        swap();
        return res;
    }

    //取得栈顶的元素
    public int peek(){
        if(queue.isEmpty()){
            throw new RuntimeException("The Stack Is Empty!");
        }
        while(queue.size() != 1){
            help.add(queue.poll());
        }
        int res = queue.peek();
        help.add(queue.poll());
        swap();
        return res;
    }

    //交换两个队列的引用
    private void swap(){
        Queue<Integer> tem = help;
        help = queue;
        queue = tem;
    }

}

两个栈表示队列:

  1. 准备两个队列,push和pop
  2. 进队操作:将进入队列的数放进push栈
  3. 出队操作:
    1. 直接从pop栈中取出元素返回
    2. 把pop栈中的元素取完后,把push栈中的所有元素取出放到pop栈中
public class StackToQueue{

	//用两个栈表示队列
	private Stack<Integer> stackPush;
	private Stack<Integer> stackPop;

	//初始化
	public StackToQueue(){
	    stackPush = new Stack<Integer>();
	    stackPop = new Stack<Integer>();
	}
	
	//进队列
	public void push(int pushInt){
	    stackPush.push(pushInt);
	}
	
	//出队列   直接从stackPop栈里pop出元素返回  
	//stackPop栈的元素pop完后,再把stackPush栈里的所有元素pop到stackPop栈
	public int poll(){
	    if(stackPop.empty() && stackPush.empty()){
	        throw new RuntimeException("The Queue Is Empty!");
	    } else if(stackPop.empty()){
	        while(!stackPush.empty()){
	            stackPop.push(stackPush.pop());
	        }
	    }
	    return stackPop.pop();
	}
	
	//取得队列头的元素
	public int peek(){
	    if(stackPop.empty() && stackPush.empty()) {
	        throw new RuntimeException("The Queue Is Empty!");
	    } else if(stackPop.empty()){
	        while(!stackPush.empty()){
	            stackPop.add(stackPush.pop());
	        }
	    }
	    return stackPop.peek();
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值