队列————链表实现
Posted crel-devi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了队列————链表实现相关的知识,希望对你有一定的参考价值。
队列的链表实现
Queue.h:
#ifndef QUEUE_H #define QUEUE_H typedef char ElementType; struct Node;//队列节点的结构体 typedef struct Node *PtrToNode; struct PtrsToList;//指向队列节点的结构体 typedef struct PtrsToList *Queue; int IsEmpty(Queue Q); Queue CreatQueue(); void MakeEmpty(Queue Q); void Enqueue(Queue Q, ElementType X); void Dequeue(Queue Q); ElementType Front(Queue Q); ElementType FrontAndDequeue(Queue Q); void PrintQueue(Queue Q); #endif
LinkedQueue.c:
#include"Queue.h" #include<stdio.h> #include<stdlib.h> struct Node{ ElementType Element; PtrToNode Next; }; struct PtrsToList{ PtrToNode Rear; PtrToNode Front; }; int IsEmpty(Queue Q) { return Q->Front == NULL;//Q->Rear == NULL; } Queue CreatQueue() { Queue Q; Q = (Queue)malloc(sizeof(struct PtrsToList)); if(Q == NULL) printf("Malloc failure!"); else { Q->Rear = Q->Front = NULL; MakeEmpty(Q); } return Q; } void MakeEmpty(Queue Q) { if(Q == NULL) printf("Please creatqueue first!"); else { while(!IsEmpty(Q)) Dequeue(Q); } } void DiseposeQueue(Queue Q) { PtrToNode P, Tmp; P = Q->Front; while(P != NULL) { Tmp = P->Next; free(P); P = Tmp; } Q->Front = Q->Rear = NULL; free(Q); } void Enqueue(Queue Q, ElementType X) { PtrToNode TmpNode; TmpNode = (PtrToNode)malloc(sizeof(struct Node)); if(TmpNode == NULL) printf("Malloc failure!"); else { TmpNode->Element = X; TmpNode->Next = NULL; if(IsEmpty(Q))//进队的是第一个元素 { Q->Front = TmpNode; Q->Rear = TmpNode; } else { Q->Rear->Next = TmpNode; Q->Rear = TmpNode; } } //Q = NULL;用来测试Q其实是传来指针的副本 } void Dequeue(Queue Q) { PtrToNode FrontNode; if(!IsEmpty(Q)) { FrontNode = Q->Front; if(Q->Front == Q->Rear)//只有一个元素在队中 Q->Front = Q->Rear = NULL; else Q->Front = Q->Front->Next; free(FrontNode); } } ElementType Front(Queue Q) { if(!IsEmpty) return Q->Front->Element; printf("Queue is empty!"); return 0; } ElementType FrontAndDequeue(Queue Q) { PtrToNode FrontCell; ElementType FrontElement; if(!IsEmpty(Q)) { FrontCell = Q->Front; if(Q->Front == Q->Rear) Q->Front = Q->Rear = NULL; else Q->Front = Q->Front->Next; FrontElement = FrontCell->Element; free(FrontCell); } return FrontElement; } void PrintQueue(Queue Q) { PtrToNode Pt; Pt = Q->Front; while(Pt->Next != NULL) { printf("%c-", Pt->Element); Pt = Pt->Next; } printf("%c ", Pt->Element); }
以上是关于队列————链表实现的主要内容,如果未能解决你的问题,请参考以下文章