一、链式队列
队列不仅可以用顺序存储,也可以向单链表一样,用链式存储,只不过队列链式存储需要头指针(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;
}