数据结构与算法——链式队列的c++实现

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值