最近閒來無事,不想浪費青春,就動手翻看之前的筆記和書本,將做一些記錄
下面是通過C語言實現的隊列:
#include #include#include typedef struct Node { int data; struct Node *next; }*Node; typedef struct Queue { int size; struct Node *first; struct Node *end; }*Queue; #define MAX_SIZE 10 Queue CreatEmptyQueue() { Queue queue = NULL; queue = (Queue)malloc(sizeof(struct Queue)); if(queue==NULL){ printf("malloc mem error !\n"); exit(-1); } queue->size = 0; queue->first = NULL; queue->end = NULL; return queue; } int isEmpty(Queue queue) { return (queue->size <= 0); } int isFull(Queue queue) { return (queue->size >= MAX_SIZE); } int QueueIn(Queue queue,int data) { assert(queue!=NULL); Node p = NULL; if(isFull(queue)){ printf("in queue error ! The Queue is full\n"); return ; } p = (Node)malloc(sizeof(struct Node)); if(p == NULL){ printf("malloc mem error!\n"); return -1; } p -> data = data; p->next = NULL; if(isEmpty(queue) == 1){ queue->first = p; queue->end = p; }else{ queue->end->next = p; queue->end = p; } queue->size = queue->size +1; return 0; } int QueueOut(Queue queue,int *data) { assert(queue!=NULL&&data!=NULL); Node p; if(isEmpty(queue)==1){ printf("Queue is empty !\n"); return -1; } p = queue->first; *data = p->data; queue->first = queue->first->next; queue->size = queue->size -1; if(isEmpty(queue)==1){ queue -> end = NULL; queue->first = NULL; } free(p); return 0; } void printQueue(Queue queue) { assert(queue!=NULL); printf("queue size id :%d\n",queue->size); Node p; p = queue->first; while(p!=NULL){ printf(" %d ",p->data); p = p->next; } printf("\n\n"); } void destoryQueue(Queue queue) { assert(queue!=NULL); Node p,q; if(isEmpty(queue)!=1){ q = p = queue->first; while(p!=NULL){ queue ->size = queue->size-1; printf("have %d node\n",queue->size); q = p->next; free(p); p = q; } } queue -> first = NULL; queue->end = NULL; free(queue); queue = NULL; } int main(int argc,char *argv[]) { Queue queue = NULL; int data; int i; int ret; printf("Enter main!\n"); queue = CreatEmptyQueue(); ret = QueueOut(queue,&data); if(ret == 0){ printf("read success data is :%d\n",data); }else{ printf("The queue is empty ,not havs data\n"); } for(i=0;i 代碼的缺陷應該還有不少,但,該代碼都是我在ubuntu 上gcc編譯通過的。如果有什麼問題,歡迎指出來,感激不盡。