码迷,mamicode.com
首页 > 其他好文 > 详细

栈和队列----由两个栈组成队列

时间:2018-07-08 15:36:13      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:ISE   删除   一个队列   create   com   empty   栈和队列   必须   --   

由两个栈组成队列

 

由两个栈实现一个队列,支持队列的基本操作(add poll peek),需要注意的是,stackPush向stackPop中压入数据,必须一次性的把stackPush中的元素全部压入,此外,如果stackPop不为空,不能向stackPop中压入数据。

 

package com.test;

import java.util.Stack;

/**
 * Created by Demrystv.
 */
public class TwoStacksQueue {
    Stack<Integer> stackPush = new Stack<Integer>();
    Stack<Integer> stackPop = new Stack<Integer>();

    public void add(int pushInt){
        stackPush.push(pushInt);
    }

    //poll是检索并删除这个队列的头
    public int poll(){
        if(stackPop.isEmpty() && stackPush.isEmpty()){
            throw new RuntimeException("Queue is empty.");
        }else if (stackPop.isEmpty()){
            while (!stackPush.isEmpty()){
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.pop();
    }

    //peek是检索但不删除这个队列的头
    public int peek(){
        if(stackPop.isEmpty() && stackPush.isEmpty()){
            throw new RuntimeException("Queue is empty.");
        }else if (stackPop.isEmpty()){
            while (!stackPush.isEmpty()){
                stackPop.push(stackPush.pop());
            }
        }
        return stackPop.peek();
    }
}

 

栈和队列----由两个栈组成队列

标签:ISE   删除   一个队列   create   com   empty   栈和队列   必须   --   

原文地址:https://www.cnblogs.com/Demrystv/p/9279974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!