数组实现栈和队列

简介: 数组实现栈和队列

用数组实现不超过固定大小的队列和栈

栈:正常使用

队列:环形数组

package com.harrison.class02;
//数组实现队列
public class Code05_RingArray {
  public static class MyQueue{
    private int[] arr;
    private int pushIndex;//end
    private int pollIndex;//begin
    private int size;
    @SuppressWarnings("unused")
    private final int limit;
    public MyQueue(int limit) {
      arr=new int[limit];
      pushIndex=0;
      pollIndex=0;
      size=0;
      this.limit=limit;
    }
    public void push(int value) {
      if(size==limit) {
        throw new RuntimeException("队列满了,不能再加了!");
      }
      size++;
      arr[pushIndex]=value;
      pushIndex=nextIndex(pushIndex);
    }
    public int pop() {
      if(size==0) {
        throw new RuntimeException("队列空了,不能再拿了!");
      }
      size--;
      int ans=arr[pollIndex];
      pollIndex=nextIndex(pollIndex);
      return ans;
    }
    public boolean isEmpty() {
      return size==0;
    }
    public int nextIndex(int i) {
      return i<size-1?i+1:0;
    }
  }
}
相关文章
|
2天前
|
存储 算法 调度
数据结构与算法-栈篇
数据结构与算法-栈篇
10 3
|
2天前
|
算法 调度 Python
数据结构与算法-队列篇
数据结构与算法-队列篇
10 3
|
2天前
数据结构初阶 队列
数据结构初阶 队列
4 0
|
2天前
数据结构初阶 栈
数据结构初阶 栈
7 1
|
7天前
|
算法
数据结构和算法学习记录——栈和队列作业(实现链栈上的进栈、实现链栈上的退栈、实现链队上的入队列)
数据结构和算法学习记录——栈和队列作业(实现链栈上的进栈、实现链栈上的退栈、实现链队上的入队列)
10 0
|
7天前
|
存储 算法
数据结构和算法学习记录——设计循环队列(数组实现循环队列)核心思路、题解过程、完整题解
数据结构和算法学习记录——设计循环队列(数组实现循环队列)核心思路、题解过程、完整题解
12 1
|
7天前
|
算法 C语言
数据结构和算法学习记录——栈和队列习题-用队列实现栈、用栈实现队列(核心思路、解题过程、完整题解)二
数据结构和算法学习记录——栈和队列习题-用队列实现栈、用栈实现队列(核心思路、解题过程、完整题解)二
14 2
|
15天前
|
存储 Java 容器
深入浅出 栈和队列(附加循环队列、双端队列)
深入浅出 栈和队列(附加循环队列、双端队列)
|
9天前
|
存储 缓存 算法
【数据结构】栈和队列的模拟实现(两个方式实现)
【数据结构】栈和队列的模拟实现(两个方式实现)
|
7天前
|
算法 C语言
数据结构和算法学习记录——栈和队列习题-用队列实现栈、用栈实现队列(核心思路、解题过程、完整题解)一
数据结构和算法学习记录——栈和队列习题-用队列实现栈、用栈实现队列(核心思路、解题过程、完整题解)一
13 0