队列相关

来源:互联网 发布:黑帽seo技术论坛 编辑:程序博客网 时间:2024/06/08 03:08
/**********队列相关************/ #include <stdio.h>#include<stdlib.h>#include<time.h>#define OK 1#define OVERFLOW 0#define error 0typedef struct Qnode /*结点结构*/ {int data;struct Qnode *next;}Qnode,*Queueptr;typedef struct     /*队列的链表结构*/{Queueptr front,rear;}LinkQueue;/*构造一个空队列Q*/int InitQueue(LinkQueue *Q){Q->front=Q->rear=(Queueptr)malloc(sizeof(Qnode));if(!Q->front)exit(OVERFLOW);Q->front->next=NULL;return OK;}/*从头到尾依次对队列Q中每个元素输出*/int QueueTraverse(LinkQueue *Q){Queueptr p;p=Q->front;while(p){printf("%d ",p->data);p=p->next;}printf("\n");return OK;}/*插入元素为e的新的队尾元素*/ int EnQueue(LinkQueue *Q,int e){Queueptr s=(Queueptr)malloc(sizeof(Qnode));if(!s)exit(OVERFLOW);s->data=e;s->next=NULL;Q->rear->next=s;Q->rear=s;return OK;}/*出队操作*/ int DeQueue(LinkQueue *Q,int *e){Queueptr p;if(Q->front==Q->rear)return error;p=Q->front;/*将欲删除的队头结点暂存给p*/*e=p->data;/*将要删除的结点的值赋给e*/ Q->front=p->next;if(Q->rear==p)/*若队头就是队尾,则删除后将rear指向头结点*/Q->rear=Q->front;free(p);return OK;}int main(int argc, char *argv[]){int i,j,opp,d;LinkQueue p;InitQueue(&p);printf("\n1.给队列赋初始值 \n2.遍历队列 \n3.入队 \n4.出队");    printf("\n0.退出 \n请选择你的操作:\n");    while(opp!=0)    {scanf("%d",&opp);switch(opp){case 1:srand(time(NULL));for(i=1;i<=10;i++){d=rand()%100+1;EnQueue(&p,d);}QueueTraverse(&p);break;case 2: QueueTraverse(&p); break; case 3: printf("请输入要入队的元素:"); scanf("%d",&d);  EnQueue(&p,d);QueueTraverse(&p); break; case 4: DeQueue(&p,&d); printf("要删除的元素值为:%d\n",d); break; case 0: exit(0);}    }    return 0;}

0 0
原创粉丝点击