由两个栈组成的队列

简介: <pre code_snippet_id="1552910" snippet_file_name="blog_20160109_1_31286" name="code" class="java">package stackAndQueue;import java.util.Stack;import org.junit.Test;/** * 由两个栈组成的队列:TwoStack
package stackAndQueue;

import java.util.Stack;

import org.junit.Test;

/**
 * 由两个栈组成的队列:TwoStackQueue【2】
 * 
 * 【编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)】
 * 
 * 设计思路:栈-先进后出,队列-先进先出。用两个栈把顺序反过来。
 * 
 * stackPush只管进栈,stackPop只管出栈且【仅当】其为空时,将stackPush的元素【全部】转移到stackPop。
 * 
 * @author xiaofan
 */
public class TwoStackQueue {
    private Stack<Integer> stackPush;

    private Stack<Integer> stackPop;

    public TwoStackQueue() {
        this.stackPush = new Stack<Integer>();
        this.stackPop = new Stack<Integer>();
    }

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

    public int poll() {
        tranfer();
        return this.stackPop.pop();
    }

    public int peek() {
        tranfer();
        return this.stackPop.peek();
    }

    private void tranfer() {
        if (this.stackPop.empty()) {
            if (this.stackPush.isEmpty()) { // isEmpty是Stack继承的Vector的方法
                throw new RuntimeException("Your queue is empty.");
            }
            while (!this.stackPush.empty()) { // empty是Stack自带的方法
                this.stackPop.push(this.stackPush.pop());
            }
        }
    }

    /////// 测试方法//////
    @Test
    public void test() {
        TwoStackQueue queue = new TwoStackQueue();
        queue.add(1);
        queue.add(2);
        queue.add(3);
        queue.add(3);
        queue.add(4);
        System.out.println("peek:" + queue.peek());
        while (true) { // 未重写empty方法,只能这样遍历
            try {
                System.out.println(queue.poll());
            } catch (Exception e) {
                break;
            }
        }
        TwoStackQueue queue1 = new TwoStackQueue();
        queue1.peek(); // java.lang.RuntimeException: Your queue is empty.
    }
}


代码地址:https://github.com/zxiaofan/Algorithm/tree/master/src/stackAndQueue


目录
相关文章
|
18天前
|
消息中间件 存储 搜索推荐
深入理解栈和队列(二):队列
深入理解栈和队列(二):队列
33 0
|
19天前
|
存储 算法 索引
【算法与数据结构】队列的实现详解
【算法与数据结构】队列的实现详解
|
1天前
|
C语言
数据结构中顺序栈的进栈和出栈用C语言表示
数据结构中顺序栈的进栈和出栈用C语言表示
11 1
|
11天前
|
存储 算法 调度
数据结构期末复习(3)栈和队列
数据结构期末复习(3)栈和队列
18 0
|
23天前
|
算法 C语言
【算法与数据结构】 C语言实现单链表队列详解2
【算法与数据结构】 C语言实现单链表队列详解
|
23天前
|
存储 算法 C语言
【算法与数据结构】 C语言实现单链表队列详解1
【算法与数据结构】 C语言实现单链表队列详解
|
23天前
|
存储 缓存 算法
【算法与数据结构】栈的实现详解
【算法与数据结构】栈的实现详解
|
23天前
|
存储 算法 编译器
【数据结构】栈算法(算法原理+源码)
【数据结构】栈算法(算法原理+源码)
【数据结构】栈算法(算法原理+源码)
|
27天前
|
存储
【数据结构】什么是栈?
【数据结构】什么是栈?
28 0
【数据结构】什么是栈?
|
1月前
|
存储 设计模式 算法
【C/C++ 数据结构 线性表】深入理解与实现栈:从基础到应用的全面探索
【C/C++ 数据结构 线性表】深入理解与实现栈:从基础到应用的全面探索
52 0