赞
踩
队列是先入先出的,即先入队的数据先出队
下面程序是队列的顺序存储结构的实现,具有入队,出队,求队列长度的的功能
#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;
// 初始化队列 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; }
代码实现结果:
输入要入队列元素的个数为4,依次输入5,6,89,45,结果输出为5 6 89 45
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。