OPSL
努力成为一名优秀的前端开发者!

文件概述

  • queue.h  存放队列(队列结点结构以及结点指针),并对队列的操作函数进行声明
  • queue.c  对之前在queue.h中声明的队列的操作函数进行定义

代码

  queue.h

 1 typedef int ElementType;
 2 typedef struct QNode * Queue;
 3 struct Node{
 4     struct Node * Next;
 5     ElementType Data;
 6 };
 7 struct QNode{
 8     struct Node * front;
 9     struct Node * rear;
10 };
11 
12 Queue CreateQueue();                    //生成空队列
13 void AddQ(Queue Q,ElementType item);    //将数据元素 item 插入队列 Q 中
14 int IsEmpty(Queue Q);                   //判断队列 Q 是否为空
15 ElementType DeleteQ(Queue Q);           //将队头数据元素从队列中删除并返回

  queue.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include "queue.h"
 4 
 5 //生成空队列
 6 Queue CreateQueue(int MaxSize){
 7     Queue tempQueue = (Queue)malloc(sizeof(QNode));
 8     tempQueue->front = NULL;
 9     tempQueue->rear = NULL;
10 }
11 
12 //将数据元素 item 插入队列 Q 中
13 void AddQ(Queue Q, ElementType item){
14     struct Node * tempNode = (struct Node *)malloc(sizeof(struct Node));
15     tempNode->Data = item;
16     tempNode->Next = NULL;
17     if(IsEmpty(Q)){
18         Q->front = tempNode;
19         Q->rear = tempNode;
20     }
21     else{
22         Q->rear->Next = tempNode;
23         Q->rear = tempNode;
24     }
25     return;
26 }
27 
28 //判断队列 Q 是否为空
29 int IsEmpty(Queue Q){
30     return (Q->front == NULL);
31 }
32 
33 //将队头数据元素从队列中删除并返回
34 ElementType DeleteQ(Queue Q){
35     if(IsEmpty(Q)){
36         printf("Error");
37         return;
38     }
39     struct Node *tempNode = Q->front;
40     ElementType tempValue = tempNode->Data;
41     if(Q->front == Q->rear){
42         Q->front = Q->rear = NULL;
43     }
44     else{
45         Q->front = Q->front->Next;
46     }
47     free(tempNode);
48     return tempValue;
49 }

 

posted on 2020-09-13 14:45  OPSL  阅读(225)  评论(0)    收藏  举报