队列的链式实现

来源:互联网 发布:保密检查清除软件 编辑:程序博客网 时间:2024/06/15 13:12

一、链式队列

队列不仅可以用顺序存储,也可以向单链表一样,用链式存储,只不过队列链式存储需要头指针(front)和尾指针(rear),分别指向队头和队尾,数据只能在对头一端删除, 在队尾一端插入。

图示:

二、实现代码

Queue.h

#pragma once#define ElemType int//链式队列typedef struct{ElemType data;//数据域struct Node* next;//指针域}Node;typedef struct {struct Node* front;//队头指针struct Node* rear;//队尾指针}Queue,*PQueue;Node* BuyNode(ElemType val);void InitQueue(PQueue pq);//初始化队列bool Push(PQueue pq, ElemType val);//入队bool GetTop(PQueue pq, ElemType *rtval);//获取队头的值,但不删除bool Pop(PQueue pq);//出队bool IsEmpty(PQueue pq);//判断对列为空void Display(PQueue pq);//显示对列元素
Queue.cpp

#include <iostream>#include "Queue.h"using namespace std;void InitQueue(PQueue pq){pq->front = NULL;pq->rear = NULL;}Node *BuyNode(ElemType val){Node *p = (Node *)malloc(sizeof(Node));if (NULL == p) return NULL;p->data = val;p->next = NULL;return p;}bool Push(PQueue pq, ElemType val){Node *p = BuyNode(val);if (pq->rear != NULL){pq->rear->next = p;pq->rear = p;}else{pq->front = p;pq->rear = p;}return true;}bool GetTop(PQueue pq, ElemType *rtval){if (IsEmpty(pq)){return false;}*rtval = pq->front->data;return true;}bool Pop(PQueue pq){if (IsEmpty(pq)){return false;}Node *p = pq->front;pq->front = p->next;free(p);if (pq->front == NULL){pq->rear = NULL;}return true;}bool IsEmpty(PQueue pq){return pq->front == NULL;}void Display(PQueue pq){Node *p = pq->front;while (p != NULL){cout << p->data << " ";}cout << endl;}

main.cpp

#include <iostream>#include "Queue.h"using namespace std;int main(){Queue List;InitQueue(&List);for (int i = 0; i < 10; ++i){Push(&List,i);}Display(&List);Pop(&List);Display(&List);return 0;}


0 0