链队列基本操作-数据结构

来源:互联网 发布:俊知集团有救吗 编辑:程序博客网 时间:2024/05/23 11:56

链队列的基本操作,基本和严慧敏的书同步,初始化、入队、出队、队长、清空队列、销毁队列

注意清空和销毁的区别。

例代码:

#include<stdio.h>#include<string.h>#include<malloc.h>#define OK 1#define ERROR 0#define OVERFLOW -1typedef int Elemtype;typedef int Status;typedef struct LNode{Elemtype data;struct LNode *next;}LNode,*Quept;typedef struct{Quept rear;Quept front;}LinkQue;Status  InitLinkQue(LinkQue &q){q.rear=q.front=(Quept)malloc(sizeof(LNode));if(!q.front) exit(OVERFLOW);q.front->next=NULL;return OK;}bool EmptyLinkQue(LinkQue q){if(q.front->next==NULL) return true;else return false;}Status EnLinkQue(LinkQue &q,Elemtype e){    Quept p;    p=(Quept)malloc(sizeof(LNode));    if(!p) exit(OVERFLOW);    p->data=e;    p->next=NULL;    q.rear->next=p;    q.rear=p;    return OK;}Status DisplayLinkQue(LinkQue q){    Quept p;    if(EmptyLinkQue(q)) printf("The link queue is empty!\n");    else    {        p=q.front->next;        while(p!=NULL)        {            printf("%d ",p->data);            p=p->next;        }        printf("\n");    }    return OK;}int LinkQueLength(LinkQue q){    int i=0;    Quept p;    p=q.front->next;    while(p!=NULL)    {        i++;        p=p->next;    }    return i;}Status DeLinkQue(LinkQue &q,Elemtype &e){    Quept p;    if(EmptyLinkQue(q)) return ERROR;    p=q.front->next;    e=p->data;    q.front->next=p->next;    if(q.rear==p) q.rear=q.front;  //just one elem left in the queue,delete it,queue is empty,q.rear also have to update to NULL    free(p);    return OK;}Status DestroyLinkQue(LinkQue &q){    while(q.front)    {        q.rear=q.front->next;        free(q.front);        q.front=q.rear;    }    return OK;}Status ClearLinkQue(LinkQue q){    Quept p,r;    q.rear=q.front;    p=q.front->next;    q.front->next=NULL;    while(p!=NULL)    {        r=p;        p=p->next;        free(r);    }}int main(){LinkQue linkq;int n,i,len;Elemtype e;InitLinkQue(linkq);if(EmptyLinkQue(linkq)) printf("The initial queue is empty.\n");printf("Input the number of queue n:");scanf("%d",&n);for(i=0;i<n;i++)    {        scanf("%d",&e);        EnLinkQue(linkq,e);    }DisplayLinkQue(linkq);len=LinkQueLength(linkq);printf("The link queue length is %d.\n",len);printf("Now dequeue.\n");DeLinkQue(linkq,e);printf("After dequeue:\n");DisplayLinkQue(linkq);printf("And the dequeue elem is %d.\n",e);len=LinkQueLength(linkq);printf("The link queue length is %d.\n",len);printf("Clear the link queue:\n");ClearLinkQue(linkq);len=LinkQueLength(linkq);printf("The link queue length is %d.\n",len);DestroyLinkQue(linkq);printf("Destroy the link queue.\n");return 0;}


0 0