每天一个小程序(9)——链队

来源:互联网 发布:sql语句查询两张表 编辑:程序博客网 时间:2024/05/22 05:18
#include <stdio.h>#include <stdlib.h>typedef int datatype;typedef struct node{datatype data;struct node *next;}QNode;typedef struct{QNode *front,*rear;}LQueue;//链队//初始化LQueue* Init_LQueue(){LQueue* q;QNode *p;q = (LQueue*)malloc(sizeof(LQueue));p = (QNode*)malloc(sizeof(QNode));p->next = NULL;q->front = q->rear = p;return q;}//入队void In_LQueue(LQueue* q,datatype x){QNode* p;p = (QNode*)malloc(sizeof(QNode));p->data = x;p->next = NULL;q->rear->next = p;//将p连接到尾部q->rear = p;//使rear指向新的尾部}//判队空int Empty_LQueue(LQueue* q){if(q->front == q->rear)return 1;elsereturn 0;}//出队int Out_LQueue(LQueue* q,datatype *x){QNode* p;if(Empty_LQueue(q))return 0;else{p = q->front->next;//将队头的第一个元素赋予pq->front->next = p->next;//将第二个元素放在队头的next*x = p->data;free(p);if(q->front->next == NULL)q->rear = q->front;return 1;}}void main(){LQueue* q = Init_LQueue();int data;printf("入队:\n");scanf("%d",&data);while(data != -1){In_LQueue(q,data);scanf("%d",&data);}printf("\n出队:\n");while(Out_LQueue(q,&data)){printf("%d ",data);}printf("\n");}





小结

    队列是限定仅能在表尾一端进行插入,表头一端进行删除操作的线性表;
    队列中的元素具有先进先出的特点;
    队头、队尾元素的位置分别由称为队头指针和队尾指 针的变量指示。 
   入队操作要修改队尾指针,出队操作要修改队头指针。    
      

0 0
原创粉丝点击