队列的链式实现

来源:互联网 发布:知臣女装旗舰店 编辑:程序博客网 时间:2024/05/16 23:46
/************************************************************************//*                    队列的链式实现                                    *//************************************************************************/#include <stdio.h>#include <STDLIB.H>#define _ERROR 0#define _OK 1typedef int QElementType;typedef int status;typedef struct QNode{QElementType data;struct QNode *next;//下一个节点} QNode,*QueuePtr;/*队列的数据抽象*/typedef struct {QueuePtr front;//队首指针(出队)[指向准出队元素]QueuePtr rear;//队尾指针(入队)[指向刚入队元素]}LinkQueue;/*队列的初始化*/status InitQueue(LinkQueue &Q){Q.front=NULL;Q.rear=NULL;return _OK;}/*判断队列是否为空*/bool IsEmpty(LinkQueue Q){return Q.front==NULL;}/*入队*/status InQueue(LinkQueue &Q,QElementType e){//构造节点QNode *ptrNode =(QNode*) malloc(sizeof(QNode));if(!ptrNode)return _ERROR;ptrNode->data=e;ptrNode->next=NULL;if(IsEmpty(Q))//判断队列是否为空{Q.front=Q.rear=ptrNode;return _OK;}//如果不为空Q.rear->next=ptrNode;Q.rear = ptrNode;return _OK;}/*出队*/status OutQueue(LinkQueue &Q,QElementType &e){if(IsEmpty(Q))return _ERROR;QNode *tempPtr = Q.front;e=tempPtr->data;Q.front = tempPtr->next;free(tempPtr);return _OK;}/*打印队列中的元素*/void PrintQueue(LinkQueue Q){QNode *tempPtr = Q.front;while(tempPtr!=NULL){printf("%d \n",tempPtr->data);tempPtr=tempPtr->next;}}void main(){LinkQueue Q;//初始化InitQueue(Q);if(IsEmpty(Q))printf("队列此时为空\n");elseprintf("队列此时不为空\n");//入队列printf("入队列\n...........\n");InQueue(Q,1);InQueue(Q,2);InQueue(Q,3);InQueue(Q,4);//打印printf("打印队列元素\n");PrintQueue(Q);QElementType e;//出队列printf("出队列\n............\n");OutQueue(Q,e);printf("出元素%d\n",e);OutQueue(Q,e);printf("出元素%d\n",e);/*打印*/printf("打印队列元素\n");PrintQueue(Q);/*越界测试*/printf("越界测试\n..........\n");OutQueue(Q,e);OutQueue(Q,e);OutQueue(Q,e);OutQueue(Q,e);printf("正常\n");}

原创粉丝点击