C语言基于链表的队列
2014-08-10 15:53
369 查看
写了一个基于链表的队列,非常简单,只提供了初始化,判断是否为空,销毁,入队和出队操作,可以很容易的嵌入到工程中去。
只提供了很少的注释,好的代码是可以自注释的,另外如果对于C语言和队列这个数据结构较熟悉的话,看懂我的代码里的一些指针操作是很容易的。
在最下面提供了一个测试程序,也可以看成使用指南,
queue.h
queue.c
main.c
只提供了很少的注释,好的代码是可以自注释的,另外如果对于C语言和队列这个数据结构较熟悉的话,看懂我的代码里的一些指针操作是很容易的。
在最下面提供了一个测试程序,也可以看成使用指南,
queue.h
/************************************* *基于链表的队列 *作者:JK *日期:2014-08-10 *************************************/ #ifndef _QUEUE_HEADER_H_ #define _QUEUE_HEADER_H_ struct Node; typedef struct Node* Queue; typedef struct Node* pNode; typedef int ElemType; struct Node { ElemType elem; pNode next; }; pNode InitQueue(); // 初始化队列 int IsEmpty(Queue q); // 判断是否为空,返回值,空:true;非空:false void DestroyQueue(Queue q); // 销毁这个队列 ElemType Dequeue(Queue q); // 出队 void Enqueue(Queue q, ElemType e); // 入队 #endif
queue.c
#include <stdio.h> #include <stddef.h> #include <stdlib.h> #include <assert.h> #include "queue.h" pNode InitQueue() { pNode p; p = (pNode)malloc(sizeof(struct Node)); assert(p != NULL); p->next = NULL; return p; } int IsEmpty(Queue q) { assert(q != NULL); return (q->next == NULL); } void DestroyQueue(Queue q) { assert(q != NULL); pNode p; while (q->next != NULL) { p = q->next; q->next = p->next; free(p); } free(q); } ElemType Dequeue(Queue q) { assert(q != NULL); pNode p; if (!IsEmpty(q)) { p = q->next; q->next = p->next; } ElemType tmp = p->elem; free(p); return tmp; } void Enqueue(Queue q, ElemType e) { assert(q != NULL); pNode pTmp = (pNode)malloc(sizeof(struct Node)); assert(pTmp); pTmp->elem = e; pTmp->next = NULL; pNode p = q; while(p->next != NULL) { p = p->next; } p->next = pTmp; }
main.c
#include <stdio.h> #include <stdlib.h> #include "queue.h" int main() { printf("Hello world JK!\n"); Queue myQueue = InitQueue(); // 初始化 int i = 0; for (i = 0; i < 10; ++i) // 入队操作 { Enqueue(myQueue, i); } while (!IsEmpty(myQueue)) // 出队操作 { int tmp = Dequeue(myQueue); printf("%d ", tmp); } DestroyQueue(myQueue); // 销毁队列 return 0; }测试结果: