#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
#define MAXQSIZE 10
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
// 节点定义
typedef struct Qnode
{
int data;
struct Qnode* next;
}Qnode, *QueuePtr;
// 链式队列定义
typedef struct LinkQueue
{
QueuePtr front; // 队头指针 —— 结构体指针
QueuePtr rear; // 队头指针 —— 结构体指针
};
// 初始化
int InitLinkQueue(LinkQueue& Q)
{
Q.front = Q.rear = new Qnode; // 创建一个头结点,让开辟的头结点的地址赋值给 头指针和尾指针,两个都指向节点
if (!Q.front) exit(OVERFLOW);
Q.front->next = nullptr;
return OK;
}
// 销毁链队
bool DestoryLinkQueue(LinkQueue& Q)
{
// 这里使用一个新的指针 p 操作
while (Q.front)
{
Qnode* p = Q.front->next; // 创建一个 Qnode 类型的指针 p;让 p 指向 Q.front 的下一个节点处
delete Q.front; // 销毁 Q.front 指针指向的队头节点
Q.front = p; // 让 队头指针 Q.front 移动到 指针 p所在的节点
}
// 但是完全可以利用 Q.rear 进行操作,因为Q.rear完全没用到,所以可以利用尾指针
//while (Q.front)
//{
// Q.rear = Q.front->next; // 直接利用尾指针;让 尾指针Q.rear 指向 Q.front 的下一个节点处
// delete Q.front; // 销毁 Q.front 指针指向的队头节点
// Q.front = Q.rear; // 让 队头指针 Q.front 移动到 尾指针 Q.rear 所在的节点
//}
return true;
}
// 链队元素入队:尾进头出
bool EnQueue(LinkQueue& Q, int e)
{
Qnode* p = new Qnode;
if (!p) exit(OVERFLOW);
p->data = e;
p->next = nullptr;
Q.rear->next = p; // 连接上 p
Q.rear = p; // 将尾指针移动到新加入的节点上
return true;
}
// 链队元素出队
int DeQueue(LinkQueue& Q, int& e)
{
if (Q.front == Q.rear)
{
cout << "队列已经空了!" << endl;
return false;
}
Qnode* p; // 创建指针 p
p = Q.front->next; // 将 p 指向首元节点
e = p->data;
Q.front->next = p->next;
if (Q.rear == p) Q.rear = Q.front; // 如果只有头尾两个节点,直接让头尾指针同时指向头结点;
delete p;
}
// 求链队的队头元素
bool GetHead(LinkQueue& Q, int &e)
{
if (Q.front == Q.rear) return false;
e = Q.front->next->data;
return true;
}
// 打印链队
void PrintLinkQueue(LinkQueue Q)
{
Qnode* p = new Qnode;
p = Q.front->next;
while (p)
{
cout << p->data << endl;
p = p->next;
}
}
int main()
{
LinkQueue Q;
InitLinkQueue(Q);
EnQueue(Q, 10101);
EnQueue(Q, 1);
EnQueue(Q, 10);
EnQueue(Q, 100);
EnQueue(Q, 1000);
EnQueue(Q, 10000);
// 求队头元素
int e;
GetHead(Q, e);
cout << "队列头元素为:" << e << endl;
cout << "队列元素依次打印为:" << endl;
PrintLinkQueue(Q);
int ee;
for (int i = 0; i < 2; i++)
{
DeQueue(Q, ee);
cout << "出队元素为:" << ee << endl;
}
PrintLinkQueue(Q);
DestoryLinkQueue(Q);
return 0;
}
数据结构与算法——链式队列的c++实现
于 2023-04-10 21:27:02 首次发布