链式队列的基本运算

链式队列的定义

  1. #include <stdio.h>
  2. #include <malloc.h>
  3. typedef char ElemType;
  4. typedef struct QNode
  5. {
  6. ElemType data;
  7. struct QNode *next;
  8. } QType; /*链队中结点的类型*/
  9. typedef struct qptr
  10. {
  11. QType *front,*rear;
  12. } LinkQueue; /*链队类型*/

初始化队列

  1. void InitQueue(LinkQueue *&lq) /*lq为引用型参数*/
  2. {
  3. lq=(LinkQueue *)malloc(sizeof(LinkQueue));
  4. lq->rear=lq->front=NULL; /*初始情况*/
  5. }

入队运算

  1. void EnQueue(LinkQueue *&lq,ElemType x) /*入队运算,lq为引用型参数*/
  2. {
  3. QType *s;
  4. s=(QType *)malloc(sizeof(QType)); /*创建新结点,插入到链队的末尾*/
  5. s->data=x;s->next=NULL;
  6. if (lq->front==NULL && lq->rear==NULL) /*空队*/
  7. lq->rear=lq->front=s;
  8. else
  9. {
  10. lq->rear->next=s;
  11. lq->rear=s;
  12. }
  13. }

出队运算

  1. int DeQueue(LinkQueue *&lq,ElemType &x) /*出队运算,lq和x均为引用型参数*/
  2. {
  3. QType *p;
  4. if (lq->front==NULL && lq->rear==NULL) /*空队*/
  5. return 0;
  6. p=lq->front;
  7. x=p->data;
  8. if (lq->rear==lq->front) /*若原队列中只有一个结点,删除后队列变空*/
  9. lq->rear=lq->front=NULL;
  10. else
  11. lq->front=lq->front->next;
  12. free(p);
  13. return 1;
  14. }

取队头元素运算

  1. int GetHead(LinkQueue *lq,ElemType &x) /*取队头元素运算,x为引用型参数*/
  2. {
  3. if (lq->front==NULL && lq->rear==NULL) /*队空*/
  4. return 0;
  5. x=lq->front->data;
  6. return 1;
  7. }

判断队空运算

  1. int QueueEmpty(LinkQueue *lq) /*判断队空运算*/
  2. {
  3. if (lq->front==NULL && lq->rear==NULL)
  4. return 1;
  5. else
  6. return 0;
  7. }

main

  1. void main()
  2. {
  3. LinkQueue *lq;
  4. ElemType e;
  5. InitQueue(lq);
  6. printf("队%s\n",(QueueEmpty(lq)==1?"空":"不空"));
  7. printf("a进队\n");EnQueue(lq,'a');
  8. printf("b进队\n");EnQueue(lq,'b');
  9. printf("c进队\n");EnQueue(lq,'c');
  10. printf("d进队\n");EnQueue(lq,'d');
  11. printf("队%s\n",(QueueEmpty(lq)==1?"空":"不空"));
  12. GetHead(lq,e);
  13. printf("队头元素:%c\n",e);
  14. printf("出队次序:");
  15. while (!QueueEmpty(lq))
  16. {
  17. DeQueue(lq,e);
  18. printf("%c ",e);
  19. }
  20. printf("\n");
  21. }