队列的链表实现

来源:互联网 发布:黄蓝带炒股软件 编辑:程序博客网 时间:2024/05/21 11:28

数据结构与算法分析——c语言描述 第三章 队列的链表实现

虽然是用链表实现,但队列头文件可不能有链表的函数,封装隐藏起来,所以在.c文件里,函数前面加了一个static,相当于c++的private下的函数。用脑想一想拆分功能,模块化。


2016.3.25更新,以前的版本是rear在最全,front在最后。上课听了老师讲后,改成front在前,rear在后,省去了遍历,复杂度为O(1)。


queue_cursor.h

typedef int ElementType;#ifndef _queue_cursor_h#define _queue_cursor_hstruct QueueRecord;typedef struct QueueRecord *Queue;struct Node;typedef struct Node *PtrToNode;typedef PtrToNode List;typedef PtrToNode Position;int IsEmpty(Queue Q);Queue CreateQueue();void DisposeQueue(Queue Q);void MakeEmpty(Queue Q);void Enqueue(ElementType X, Queue Q);ElementType Front(Queue Q);void Dequeue(Queue Q);ElementType FrontAndDequeue(Queue Q);#endif



queue_cursor.c

#include "queue_cursor.h"#include "fatal.h"#include <stdlib.h>struct QueueRecord {List L;PtrToNode Rear;int Size;};struct  Node {ElementType Element;Position Next;};static void DeleteList(List L) {Position p;p = L->Next;L->Next = NULL;while (p != NULL) {Position tmp;tmp = p->Next;free(p);p = tmp;}}static void DisposeList(List L) {DeleteList(L);free(L);}static void Insert(ElementType X, Queue Q, Position P) {Position tmpCell;tmpCell = malloc(sizeof(struct Node));if (tmpCell == NULL)FatalError("Out of space!!");tmpCell->Element = X;if (P->Next == NULL)Q->Rear = tmpCell;tmpCell->Next = P->Next;P->Next = tmpCell;}static List creatList() {List L = malloc(sizeof(struct Node));if (L == NULL)Error("out of memory");L->Next = NULL;return L;}int IsEmpty(Queue Q) {return Q->Size == 0;}Queue CreateQueue() {Queue q;q = malloc(sizeof(struct QueueRecord));if (q == NULL)Error("out of memory");q->L = creatList();q->Rear = q->L;q->Size = 0;return q;}void DisposeQueue(Queue Q) {if (Q != NULL) {DisposeList(Q->L);free(Q);}}void MakeEmpty(Queue Q) {DeleteList(Q->L);Q->Rear = Q->L;Q->Size = 0;}void Enqueue(ElementType X, Queue Q) {Insert(X, Q, Q->Rear);Q->Size++;}ElementType Front(Queue Q) {if (IsEmpty(Q))Error("Empty queue");return Q->L->Next->Element;}void Dequeue(Queue Q) {if (IsEmpty(Q))Error("Empty queue");Position temp = Q->L->Next->Next;free(Q->L->Next);Q->L->Next = temp;Q->Size--;}ElementType FrontAndDequeue(Queue Q) {ElementType X = Front(Q);Dequeue(Q);return X;}





main.c

#include<stdlib.h>#include<stdio.h>#include"queue_cursor.h"int main() {Queue q = CreateQueue();for (int i = 0; i < 8; i++){Enqueue(i, q);}printf("%d\n", FrontAndDequeue(q));printf("%d\n", FrontAndDequeue(q));printf("%d\n", FrontAndDequeue(q));}


0 0
原创粉丝点击