链式队列(c语言)
define.h
1 // define.h 2 #ifndef __MENGQL_DEFINE__ 3 #define __MENGQL_DEFINE__ 4 5 #define C_LOG_DBG(format, ...) 6 //printf("[%s@%s,%d] " format ,__FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__); 7 #define C_LOG_ERR(format, ...) printf("[%s@%s,%d] " format ,__FUNCTION__, __FILE__, __LINE__, ##__VA_ARGS__); 8 typedef enum EStatus {ERROR, OK} Status; 9 10 #endif
LinkQueue.h
1 // LinkQueue.h 2 #ifndef __LINK_QUEUE_H__ 3 #define __LINK_QUEUE_H__ 4 #include "define.h" 5 typedef struct QNode 6 { 7 QElemType data; 8 struct QNode *next; 9 }QNode, *QueuePtr; 10 11 typedef struct 12 { 13 QueuePtr front; 14 QueuePtr rear; 15 }LinkQueue; 16 17 #endif
LinkQueue.c
1 // LinkQueue.c 2 typedef int QElemType; 3 #include "LinkQueue.h" 4 #include <stdlib.h> 5 #include <stdio.h> 6 7 Status InitQueue(LinkQueue *Q) 8 { 9 Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode)); 10 if(Q->front == NULL) 11 { 12 C_LOG_ERR("%s", "malloc error!!!\n"); 13 return ERROR; 14 } 15 Q->front->next = NULL; 16 return OK; 17 } 18 Status DestroyQueue(LinkQueue *Q) 19 { 20 while(Q->front != NULL) 21 { 22 Q->rear = Q->front->next; 23 free(Q->front); 24 Q->front = Q->rear; 25 } 26 return OK; 27 } 28 Status EnQueue(LinkQueue *Q, QElemType e) 29 { 30 QueuePtr p; 31 p = (QueuePtr)malloc(sizeof(QNode)); 32 if(p == NULL) 33 { 34 C_LOG_ERR("%s", "malloc error!!!\n"); 35 return ERROR; 36 } 37 p->data = e; p->next = NULL; 38 Q->rear->next = p; 39 Q->rear = p; 40 return OK; 41 } 42 Status DeQueue(LinkQueue *Q, QElemType *e) 43 { 44 QueuePtr p; 45 if(Q->front == Q->rear) 46 { 47 C_LOG_ERR("%s", "queue is empty!!!\n"); 48 return ERROR; 49 } 50 p = Q->front->next; 51 *e = p->data; 52 Q->front = Q->front->next; 53 free(p); 54 return OK; 55 } 56 Status QueueEmpty(LinkQueue *Q) 57 { 58 if(Q->front == Q->rear) 59 { 60 return OK; 61 } 62 return ERROR; 63 } 64 65 int main() 66 { 67 LinkQueue Q; 68 QElemType e; 69 70 InitQueue(&Q); 71 EnQueue(&Q, 1); 72 EnQueue(&Q, 2); 73 EnQueue(&Q, 3); 74 EnQueue(&Q, 4); 75 EnQueue(&Q, 5); 76 while(Q.front != Q.rear) 77 { 78 DeQueue(&Q, &e); 79 printf("%d\n", e); 80 } 81 return 0; 82 }
posted on 2012-08-21 16:29 favourmeng 阅读(296) 评论(0) 编辑 收藏 举报