队列的ADT
Posted zhangleshan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了队列的ADT相关的知识,希望对你有一定的参考价值。
Queue.h
1 #ifndef QUEUE_H_INCLUDED 2 #define QUEUE_H_INCLUDED 3 #include <stdbool.h> 4 5 typedef struct queue QUEUE; 6 7 QUEUE* createQueue(void); 8 QUEUE* destroyQueue(QUEUE* queue); 9 10 bool dequeue(QUEUE* queue, void** itemPtr); 11 bool enqueue(QUEUE* queue, void* itemPtr); 12 bool queueFront(QUEUE* queue, void** itemPtr); 13 bool queueRear(QUEUE* queue, void** itemPtr); 14 int queueCount(QUEUE* queue); 15 16 bool emptyQueue(QUEUE* queue); 17 bool fullQueue(QUEUE* queue); 18 19 #endif // QUEUE_H_INCLUDED
Queue.c
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include "Queue.h" 4 5 typedef struct node 6 { 7 void* dataPtr; 8 struct node* next; 9 } QUEUE_NODE; 10 11 struct queue 12 { 13 QUEUE_NODE* front; 14 QUEUE_NODE* rear; 15 int count; 16 }; 17 18 QUEUE* createQueue(void) 19 { 20 QUEUE* queue; 21 22 queue = (QUEUE*)malloc(sizeof(QUEUE)); 23 if(queue){ 24 queue->front = NULL; 25 queue->rear = NULL; 26 queue->count = 0; 27 } 28 return queue; 29 } 30 31 QUEUE* destroyQueue(QUEUE* queue) 32 { 33 QUEUE_NODE* deletePtr; 34 35 if(queue){ 36 while(queue->front != NULL){ 37 free(queue->front->dataPtr); 38 deletePtr = queue->front; 39 queue->front = queue->front->next; 40 free(deletePtr); 41 } 42 free(queue); 43 } 44 return NULL; 45 } 46 47 bool dequeue(QUEUE* queue, void** itemPtr) 48 { 49 QUEUE_NODE* deleteLoc; 50 51 if(!queue->count) 52 return false; 53 54 *itemPtr = queue->front->dataPtr; 55 deleteLoc = queue->front; 56 if(queue->count == 1) 57 queue->rear = queue->front = NULL; 58 else 59 queue->front = queue->front->next; 60 (queue->count)--; 61 free(deleteLoc); 62 63 return true; 64 } 65 bool enqueue(QUEUE* queue, void* itemPtr) 66 { 67 QUEUE_NODE* newPtr; 68 69 if(!(newPtr = (QUEUE_NODE*)malloc(sizeof(QUEUE_NODE)))) 70 return false; 71 72 newPtr->dataPtr = itemPtr; 73 newPtr->next = NULL; 74 75 if(queue->count == 0) 76 queue->front = newPtr; 77 else 78 queue->rear->next = newPtr; 79 80 (queue->count)++; 81 queue->rear = newPtr; 82 return true; 83 } 84 bool queueFront(QUEUE* queue, void** itemPtr) 85 { 86 if(!queue->count) 87 return false; 88 else 89 { 90 *itemPtr = queue->front->dataPtr; 91 return true; 92 } 93 } 94 bool queueRear(QUEUE* queue, void** itemPtr) 95 { 96 if(!queue->count) 97 return false; 98 else 99 { 100 *itemPtr = queue->rear->dataPtr; 101 return true; 102 } 103 } 104 int queueCount(QUEUE* queue) 105 { 106 return queue->count; 107 } 108 109 bool emptyQueue(QUEUE* queue) 110 { 111 return(queue->count == 0); 112 } 113 bool fullQueue(QUEUE* queue) 114 { 115 QUEUE_NODE* temp; 116 117 temp = (QUEUE_NODE*)malloc(sizeof(*(queue->rear))); 118 if(temp){ 119 free(temp); 120 return false; 121 } 122 return true; 123 }
以上是关于队列的ADT的主要内容,如果未能解决你的问题,请参考以下文章