前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用数组结构实现大小固定的队列和栈

用数组结构实现大小固定的队列和栈

原创
作者头像
大学里的混子
修改2019-02-18 16:31:53
1K0
修改2019-02-18 16:31:53
举报
文章被收录于专栏:LeetCodeLeetCode

一.用数组结构实现大小固定的栈

代码语言:javascript
复制
public static class ArrayStack {
   private Integer[] arr;
   private Integer size;

   public ArrayStack(int initSize) {
      if (initSize < 0) {
         throw new IllegalArgumentException("The init size is less than 0");
      }
      arr = new Integer[initSize];
      size = 0;
   }

   public Integer peek() {
      if (size == 0) {
         return null;
      }
      return arr[size - 1];
   }

   public void push(int obj) {
      if (size == arr.length) {
         throw new ArrayIndexOutOfBoundsException("The queue is full");
      }
      arr[size++] = obj;
   }

   public Integer pop() {
      if (size == 0) {
         throw new ArrayIndexOutOfBoundsException("The queue is empty");
      }
      return arr[--size];
   }
}

二.用数组结构实现大小固定的队列

代码语言:javascript
复制
public static class ArrayQueue {
   private Integer[] arr;
   private Integer size;
   private Integer first;
   private Integer last;

   public ArrayQueue(int initSize) {
      if (initSize < 0) {
         throw new IllegalArgumentException("The init size is less than 0");
      }
      arr = new Integer[initSize];
      size = 0;
      first = 0;
      last = 0;
   }

   public Integer peek() {
      if (size == 0) {
         return null;
      }
      return arr[first];
   }

   public void push(int obj) {
      if (size == arr.length) {
         throw new ArrayIndexOutOfBoundsException("The queue is full");
      }
      size++;
      arr[last] = obj;
      last = last == arr.length - 1 ? 0 : last + 1;
   }

   public Integer poll() {
      if (size == 0) {
         throw new ArrayIndexOutOfBoundsException("The queue is empty");
      }
      size--;
      int tmp = first;
      first = first == arr.length - 1 ? 0 : first + 1;
      return arr[tmp];
   }
}

注意这里的size的用法。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一.用数组结构实现大小固定的栈
  • 二.用数组结构实现大小固定的队列
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档