鱼C论坛

 找回密码
 立即注册
查看: 1323|回复: 3

数据结构栈和队列问题

[复制链接]
发表于 2022-5-9 19:28:50 | 显示全部楼层 |阅读模式
20鱼币
假设以数组se[m]存放循环队列的元素,同时设置变量front和rear分别作为队头指针和队尾指针,且队头指针指向队头前一个位置,写出判定此循环队列为满的条件,并给出循环队列的入队和出队的算法

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-5-9 19:57:19 | 显示全部楼层

循环队列的队满条件为 (rear+1) % m = front

java 代码参考:

  1. public class ArrayQueue {
  2.     private int maxSize; // 数组最大容量
  3.     private int front; // 队头指针,指向队头元素的前一个位置
  4.     private int rear; // 队尾指针,指向队列尾的最后一个位置
  5.     private int[] arr; // 用数组存放数据,模拟队列

  6.     public ArrayQueue(int arrMaxSize) {
  7.         maxSize = arrMaxSize;
  8.         arr = new int[maxSize];
  9.         front = rear = 0;
  10.     }

  11.     public boolean isFull() {
  12.         return (rear + 1) % maxSize == front;
  13.     }

  14.     public boolean isEmpty() {
  15.         return rear == front;
  16.     }

  17.     public void addQueue(int n) {
  18.         if (isFull()) {
  19.             throw new RuntimeException("队列已满,不能加入数据");
  20.         }
  21.         arr[rear] = n;
  22.         rear = (rear + 1) % maxSize;
  23.     }

  24.     public int getQueue() {
  25.         if (isEmpty()) {
  26.             throw new RuntimeException("队列空,无法取出数据");
  27.         }
  28.         front = (front + 1) % maxSize;
  29.         return arr[front];
  30.     }

  31.     public void show() {
  32.         if (isEmpty()) {
  33.             System.out.println("当前队列为空!");
  34.             return;
  35.         }
  36.         System.out.print("Queue = [");
  37.         int temp = front;
  38.         for (int i = 0; i < (rear + maxSize - front) % maxSize; i++) {
  39.             if (i == (rear + maxSize - front) % maxSize - 1)  {
  40.                 System.out.print(arr[temp]);
  41.             } else {
  42.                 System.out.print(arr[temp] + ", ");
  43.             }
  44.             temp = (temp + 1) % maxSize;
  45.         }
  46.         System.out.println(']');
  47.     }

  48.     public int headQueue() {
  49.         if (isEmpty()) {
  50.             throw new RuntimeException("队列为空!");
  51.         }
  52.         return arr[front];
  53.     }
  54. }
复制代码

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2022-5-9 20:02:06 | 显示全部楼层
Twilight6 发表于 2022-5-9 19:57
循环队列的队满条件为 (rear+1) % m = front

java 代码参考:

牛啊,你们这都是咋学的呀,有没有啥学习方法推荐推荐
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-5-9 20:08:40 | 显示全部楼层
LXTTY 发表于 2022-5-9 20:02
牛啊,你们这都是咋学的呀,有没有啥学习方法推荐推荐



B站的 王卓老师数据结构与算法视频强烈推荐,虽然是基于 C/C++ 的

但是数据结构与算法本身就是学习算法实现的思想(我就没有 C/C++ 的基础,QAQ)

而且王卓老师不得不说,老师讲课很温柔,而且解释的蛮容易理解的,是我看过感觉最好的一个数据结构课程老师了(个人感觉哈)

参考视频连接:https://www.bilibili.com/video/BV1nJ411V7bd?p=1

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-24 14:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表