如何用栈结构实现队列结构

简介: 如何用栈结构实现队列结构

如何用栈结构实现队列结构:用两个栈拼队列结构

package com.harrison.class02;
import java.util.Stack;
public class Code07_TwoStacksImplementQueue {
  public static class TwoStacksToQueue{
    public Stack<Integer> pushStack;
    public Stack<Integer> popStack;
    public TwoStacksToQueue() {
      pushStack=new Stack<Integer>();
      popStack=new Stack<Integer>();
    }
    public void pushToPop() {
      if(popStack.isEmpty()) {
        while(!pushStack.isEmpty()) {
          popStack.push(pushStack.pop());
        }
      }
    }
    public void add(int pushInt) {
      pushStack.push(pushInt);
      pushToPop();
    }
    public int poll() {
      if(pushStack.isEmpty() && popStack.isEmpty()) {
        throw new RuntimeException("队列空了!");
      }
      pushToPop();
      return popStack.pop();
    }
    public int peek() {
      if(pushStack.isEmpty() && popStack.isEmpty()) {
        throw new RuntimeException("队列空了!");
      }
      pushToPop();
      return popStack.peek();
    }
  }
  public static void main(String[] args) {
    TwoStacksToQueue test=new TwoStacksToQueue();
    test.add(1);
    test.add(2);
    test.add(3);
    System.out.println(test.peek());
    System.out.println(test.poll());
    System.out.println(test.peek());
    System.out.println(test.poll());
    System.out.println(test.peek());
    System.out.println(test.poll());
  }
}
相关文章
|
5天前
数据结构(栈与列队)
数据结构(栈与列队)
11 1
|
10天前
|
存储 JavaScript 前端开发
为什么基础数据类型存放在栈中,而引用数据类型存放在堆中?
为什么基础数据类型存放在栈中,而引用数据类型存放在堆中?
37 1
|
6天前
【数据结构】-- 栈和队列
【数据结构】-- 栈和队列
9 0
|
11天前
探索数据结构:队列的的实现与应用
探索数据结构:队列的的实现与应用
|
11天前
探索顺序结构:栈的实现方式
探索顺序结构:栈的实现方式
|
11天前
|
存储 C语言
栈和队列题目练习
栈和队列题目练习
12 0
|
18天前
|
存储 算法 搜索推荐
探索常见数据结构:数组、链表、栈、队列、树和图
探索常见数据结构:数组、链表、栈、队列、树和图
84 64
|
11天前
|
算法 程序员 索引
数据结构与算法学习七:栈、数组模拟栈、单链表模拟栈、栈应用实例 实现 综合计算器
栈的基本概念、应用场景以及如何使用数组和单链表模拟栈,并展示了如何利用栈和中缀表达式实现一个综合计算器。
16 1
数据结构与算法学习七:栈、数组模拟栈、单链表模拟栈、栈应用实例 实现 综合计算器
|
11天前
初步认识栈和队列
初步认识栈和队列
36 10
|
27天前
|
算法 安全 测试技术
golang 栈数据结构的实现和应用
本文详细介绍了“栈”这一数据结构的特点,并用Golang实现栈。栈是一种FILO(First In Last Out,即先进后出或后进先出)的数据结构。文章展示了如何用slice和链表来实现栈,并通过golang benchmark测试了二者的性能差异。此外,还提供了几个使用栈结构解决的实际算法问题示例,如有效的括号匹配等。
golang 栈数据结构的实现和应用