队列的基本操作

来源:互联网 发布:大连知润科技 编辑:程序博客网 时间:2024/04/26 17:52

队列也分为顺序存储结构和链式存储结构。


下面主要介绍队列的链式存储结构基本操作。


#include <stdio.h>#include <stdlib.h>typedef char Elemtype;typedef struct qNode{Elemtype data;struct qNode *next;}qNode,*QueuePtr;typedef struct{QueuePtr front,rear;}LinkQueue;void InitQueue(LinkQueue *q){q->front=q->rear=(QueuePtr) malloc(sizeof(qNode));if( !q->front )exit(0);q->front->next=NULL;}void InsertQueue(LinkQueue *q,Elemtype e){QueuePtr p;p = (QueuePtr) malloc (sizeof(qNode));if(!p)exit(0);p->data=e;p->next=NULL;q->rear->next=p;q->rear=p;}void DeleteQueue(LinkQueue *q,Elemtype *e){QueuePtr p;if(q->front==q->rear)return;p=q->front->next;*e=p->data;q->front->next=p->next;if(p==q->rear){q->front=q->rear;}free(p);}void DestroyQueue(LinkQueue *q){while(q->front){q->rear=q->front->next;free(q->front);q->front=q->rear;}q->front=NULL;}void GetHead(LinkQueue *q){QueuePtr p=q->front->next;printf("%c\n",p->data);}void PrintQueue(LinkQueue *q){if(q->front==q->rear)exit(0);QueuePtr p=q->front->next;while(p){printf("%c   ",p->data);p=p->next;}}int main(){LinkQueue q;char c,d;InitQueue(&q);printf("请输入一串字符,并已#结束:\n");scanf("%c",&c);while(c != '#'){InsertQueue(&q,c);scanf("%c",&c);}getchar();printf("字符的第一个字符为:%c");GetHead(&q);printf("\n");printf("队列输出\n");PrintQueue(&q);printf("\n");DeleteQueue(&q,&d);printf("删除的元素为:%c\n",d);printf("新的队列输出为:\n");PrintQueue(&q);printf("\n");///*DestroyQueue(&q);printf("新的队列输出为:\n");PrintQueue(&q);printf("\n");//*/return 0;}


0 0