【C数据结构】简单链队列代码

    技术2022-07-11  92

     

    #include<stdio.h> #include<stdlib.h> typedef int datatype; typedef struct QNode{//结点 datatype data; struct QNode *next; }QNode; typedef struct qptr{ QNode *front;//指向结点的头指针 QNode *rear;//指向结点的尾指针 }LinkQueue; void InitQueue(LinkQueue* &Q);//初始化 void InQueue(LinkQueue* &Q,datatype x);//入队 int OutQueue(LinkQueue* &Q,datatype &x);//出队 int ReadFront(LinkQueue* &Q,datatype &x);//读取队头 int IsEmpty(LinkQueue* &Q);//判断是否为空 int main(){ LinkQueue *Q; int x; InitQueue(Q); printf("是否为空? %d\n",IsEmpty(Q)); printf("此时执行出队操作结果 %d\n",OutQueue(Q,x)); for(int i=0;i<5;i++){ //每入队一个就读取并打印出头元素值 InQueue(Q,i+1); ReadFront(Q,x); printf("%d ",x);//头的值不变 } printf("\n是否为空? %d\n依次出队:\n",IsEmpty(Q)); //使用出队方法循环输出 while(OutQueue(Q,x)) printf("%d ",x); printf("\n"); //只能输出一遍,下面这个while循环不会被执行 while(OutQueue(Q,x)) printf("%d ",x); } void InitQueue (LinkQueue* &Q){ Q=new LinkQueue; Q->front=NULL; Q->rear=NULL; } void InQueue(LinkQueue* &Q,datatype x){ //入队-从队尾插入 QNode *s; s=new QNode; s->data=x; s->next=NULL; if(Q->front==NULL&&Q->rear==NULL) Q->rear=Q->front=s; else{ //最后一个元素指向新的值 Q->rear->next=s; //尾指针指向新的值 Q->rear=s; } } int OutQueue(LinkQueue* &Q,datatype &x){ QNode *p; if(Q->front==NULL&&Q->rear==NULL) return 0;//取之前为空 p=Q->front; x=p->data;//赋值取出头元素的值 if(Q->rear==Q->front&&Q->rear!=NULL) Q->rear=Q->front=NULL;//取之前只剩一个元素,取之后改为空 else Q->front=Q->front->next;//移动头指针 free(p); return 1; } int ReadFront(LinkQueue *&Q,datatype &x){ if(Q->front==NULL) return 0; x=Q->front->data; return 1; } int IsEmpty(LinkQueue* &Q){ if(Q->front==NULL&&Q->rear==NULL) return 1; else return 0; }

     

    Processed: 0.010, SQL: 12