首页 > 编程知识 正文

数据结构代码C实现,拓扑排序c语言代码

时间:2023-05-04 07:32:53 阅读:132345 作者:1549

利用顺序队列(循环队列)数据结构实现一组数据的存储,并利用简单的交互实现队列的入队和出队。

//ADT 队列(Queue) 顺序存储结构 SqQueue#include <stdio.h>#include <stdlib.h>#define MAXSIZE 50#define OK 1#define ERROR 0#define TRUE 1#define FALSE 0typedef int ElemType;typedef int Status;//定义顺序队列typedef struct SqQueue{ ElemType data[MAXSIZE]; int front; //定义顺序队列的头指针 int rear; //定义顺序队列的尾指针} SqQueue;//顺序队列的初始化Status InitQueue(SqQueue *Q){ Q->front = 0; Q->rear = 0; return 0;}//判断顺序队列是否初始化成功Status QueueEmpty(SqQueue Q){ if (Q.front == 0 || Q.rear == 0) return TRUE; else return FALSE;}//清空顺序队列Status ClearQueue(SqQueue *Q){ Q->front = 0; Q->rear = 0; return OK;}//查询顺序队列中的数据元素个数Status QueueLength(SqQueue Q){ int a = 0; a = (Q.rear - Q.front + MAXSIZE) % MAXSIZE; //为提高数组空间的利用,通过对数组最大值取模构成逻辑上的循环队列 return a;}//查询顺序队列队首数据元素的值Status GetElem(SqQueue Q){ if (Q.front == Q.rear) return ERROR; printf("顺序队列队首数据元素的值为%dn", Q.data[Q.front]); return OK;}//顺序队列队尾的插入(入队)Status QueueInsert(SqQueue *Q, ElemType e){ if ((Q->rear + 1) % MAXSIZE == Q->front) //判断顺序队列是否满队 return ERROR; Q->data[Q->rear] = e; Q->rear = (Q->rear + 1) % MAXSIZE; //队尾指针后移,利用对MAXSIZE取模来构成逻辑上的循环 return OK;}//顺序队列队首的删除(出队)Status QueueDelete(SqQueue *Q, ElemType *e){ if (Q->front == Q->rear) return ERROR; *e = Q->data[Q->front]; //将出队数据元素的值传递出来 Q->front = (Q->front + 1) % MAXSIZE; return OK;}//顺序队列数据元素的输入Status CreateQueue(SqQueue *Q){ printf("请输入一组数据元素的值:"); while (TRUE) { int a = 0; scanf("%d", &a); char c = getchar(); Q->data[Q->rear] = a; Q->rear = (Q->rear + 1) % MAXSIZE; if (c == 'n') break; } return OK;}//顺序队列的主函数int main(){ SqQueue Q; ElemType e = 0; Status i = 0; printf("顺序队列初始化中......n"); i = InitQueue(&Q); i = QueueEmpty(Q); if (i == 0) printf("顺序队列初始化失败n"); else printf("顺序队列初始化成功n"); i = CreateQueue(&Q); i = QueueLength(Q); printf("数据元素存储成功,顺序队列中的数据元素个数为%dn", i); while (TRUE) { int a = 0; printf("请选择将要进行的操作:n1:查询数据元素的个数n2:查询队首数据元素的值n3:顺序队列队尾的插入n4:顺序队列队首的删除n5:清空顺序队列并结束程序n"); scanf("%d", &a); switch (a) { case 1: { int b = 0; b = QueueLength(Q); printf("顺序队列中的数据元素个数为%dn", b); break; } case 2: { int b = 0; b = GetElem(Q); if (b == 0) printf("查询失败n"); break; } case 3: { int b = 0; printf("请输入要入队的值:"); scanf("%d", &e); b = QueueInsert(&Q, e); if (b == 0) printf("入队失败n"); else printf("入队成功n"); break; } case 4: { int b = 0; b = QueueDelete(&Q, &e); if (b == 0) printf("出队失败n"); else printf("出队成功,出队数据元素的值为%dn", e); break; } case 5: { int b = 0; b = ClearQueue(&Q); if (b == 0) printf("顺序队列清空失败n"); else printf("顺序队列清空成功n"); exit(0); } default: break; } } return 0;}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。