当前位置:   article > 正文

数据结构队列顺序存储代码实现(C语言)_数据结构顺序队列完整代码

数据结构顺序队列完整代码

队列是先入先出的,即先入队的数据先出队
下面程序是队列的顺序存储结构的实现,具有入队,出队,求队列长度的的功能

  1. 程序开头
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 100
#define Ok 1
#define ERROR 0

typedef int QElemType;
typedef int Status;

typedef struct {
    QElemType *base;
    int front;
    int rear;
} Squeue;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  1. 程序主题
// 初始化队列
Status InitQueue(Squeue *s) {

    s->base = (QElemType *) malloc(MAXSIZE * sizeof(QElemType));
    if (!s->base) {
        printf("初始化队列失败");
        exit(-1);
    }
    s->front = s->rear = 0;
    return Ok;
}

// 队列的长度
Status GetLen(Squeue s){
    int len;
    len = (s.rear - s.front + MAXSIZE) % MAXSIZE;
    printf("队列的长度为:%d\n",len);
    return Ok;
}

// 插入元素到队列
 Status InsertQueue(Squeue *s, QElemType e){

    if ((s->rear + 1) % MAXSIZE == s->front){
        return ERROR;
    }
    s->base[s->rear] = e;
    s->rear = (s->rear +1 ) % MAXSIZE;

    return Ok;
}

// 输出队列的元素
Status DeQueue(Squeue *s, int *e){
    if (s->front == s->rear) {
        return ERROR;
    }
    *e = s->base[s->front];
    s->front = (s->front + 1) % MAXSIZE;
    return Ok;
}

int main(){
    int n, tmp, num;
    Squeue s;
    InitQueue(&s);
    printf("请输入要入队列元素的个数:");
    scanf("%d",&n);
    for (int i = 0; i < n; i++) {
        printf("请输入第 %d 个值:",i+1);
        scanf("%d",&tmp);
        InsertQueue(&s, tmp);
    }
    GetLen(s);
    for (int j = 0; j < n; j++) {
        DeQueue(&s,&num);
        printf("%d\t",num);

    }
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

代码实现结果:
在这里插入图片描述
输入要入队列元素的个数为4,依次输入5,6,89,45,结果输出为5 6 89 45

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/706863
推荐阅读
相关标签
  

闽ICP备14008679号