欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

数据结构C语言算法(顺序队列的创建、入队、出队、销毁等操作)

程序员文章站 2022-06-27 18:36:49
seqQueue.h#ifndef _SEQ_QUEUE_H_#define _SEQ_QUEUE_H_#include #include typedef int DataType;typedef struct list{DataType *pBase;int front;int rear;}SeqQueue;#define SEQ_QUEUE_MAX_SIZE 10extern SeqQueue *...

seqQueue.h

#ifndef _SEQ_QUEUE_H_ #define _SEQ_QUEUE_H_ #include <stdio.h> #include <stdlib.h> typedef int DataType; typedef struct list { DataType *pBase; int front; int rear; }SeqQueue; #define SEQ_QUEUE_MAX_SIZE 10 extern SeqQueue *createSeqQueue(); extern int isFullSeqQueue(SeqQueue *pList); extern int isEmptySeqQueue(SeqQueue *pList); extern void showSeqQueue(SeqQueue *pList); extern int enterSeqQueue(SeqQueue *pList,DataType data); extern int outSeqQueue(SeqQueue *pList,DataType *poutdata); extern int getLenthSeqQueue(SeqQueue * pList); extern void destroySeqQueue(SeqQueue **pList); #endif 

seqQueue.c

 #include "seqQueue.h" /*创建顺序队列*/ SeqQueue *createSeqQueue() { SeqQueue *pList = malloc(sizeof(SeqQueue)); if(NULL == pList) { perror("createSeqQueue malloc error\n"); return NULL; } pList->front = 0; pList->rear = 0; pList->pBase = malloc(sizeof(DataType) * SEQ_QUEUE_MAX_SIZE); if(NULL == pList->pBase) { perror("pBase malloc error!\n"); return NULL; } return pList; } /*判断是否为满队列*/ int isFullSeqQueue(SeqQueue *pList) { return (pList->rear + 1) % SEQ_QUEUE_MAX_SIZE == pList->front; } /*判断是否为空队列*/ int isEmptySeqQueue(SeqQueue *pList) { return pList->front == pList->rear; } /*遍历*/ void showSeqQueue(SeqQueue *pList) { int i = 0; i = pList->front; while(i != pList->rear) { printf("%d ",pList->pBase[i]); i = (i+1) % SEQ_QUEUE_MAX_SIZE; } printf("\n"); } /*入队*/ int enterSeqQueue(SeqQueue *pList,DataType data) { if(isFullSeqQueue(pList)) { return 0; } pList->pBase[pList->rear] = data; pList->rear = (pList->rear + 1) % SEQ_QUEUE_MAX_SIZE; return 0; } /*出队*/ int outSeqQueue(SeqQueue *pList,DataType *poutdata) { if(isEmptySeqQueue(pList)) { return 0; } if(poutdata != NULL) { *poutdata = pList->pBase[pList->front]; } pList->front = (pList->front + 1) % SEQ_QUEUE_MAX_SIZE; return 0; } /*获取队列长度*/ int getLenthSeqQueue(SeqQueue * pList) { return (pList->rear - pList->front + SEQ_QUEUE_MAX_SIZE) % SEQ_QUEUE_MAX_SIZE; } /*销毁队列*/ void destroySeqQueue(SeqQueue **pList) { free((*pList)->pBase); free(*pList); *pList = NULL; } 

main.c

#include "seqQueue.h" int main(int argc, const char *argv[]) { SeqQueue *pList = NULL; pList = createSeqQueue(); int i = 0; for(i = 0;i < 10;i++) { enterSeqQueue(pList,i); } showSeqQueue(pList); outSeqQueue(pList,NULL); showSeqQueue(pList); enterSeqQueue(pList,9); showSeqQueue(pList); return 0; } 

本文地址:https://blog.csdn.net/weixin_48922642/article/details/107922862