数据结构 链式队列C/C++

列队分为链式存储 与 顺序存储

下面给出小编写的顺序存储的链接https://blog.csdn.net/qq_40990854/article/details/82846939

这篇是小编写的链式存储。

思路:

队列是一个先进先出的特点,在链表的表头 head作为固定不动的,在表尾入队,在表头 head后出队

#include <iostream>
using namespace std;

typedef
	struct Node {
		int data;
		struct Node * next;
	}Node;

class ChainOfQueue
{
	Node head;
	Node * rear;
	void insertAtRear(int data);
	void deleteAtHead();
public:
	ChainOfQueue();
	~ChainOfQueue();
	void Enqueue(int data);
	void Dequeue();
	void print();
};

ChainOfQueue::ChainOfQueue()
{
	head.data = 0;
	head.next = NULL;
	rear = &head;
}


ChainOfQueue::~ChainOfQueue()
{
}

void ChainOfQueue::Enqueue(int data)
{
	Node * tmpNode = new Node;
	tmpNode->data = data;
	tmpNode->next = NULL;
	rear->next = tmpNode;
	rear = tmpNode;
}

void ChainOfQueue::insertAtRear(int data)
{
	Node * p_head = head.next;
	while (p_head != NULL) {
		p_head = p_head->next;
	}
	Node * tmpNode = new Node;
	tmpNode->data = data;
	tmpNode->next = NULL;
	p_head->next = tmpNode;
}

void ChainOfQueue::Dequeue()
{
	deleteAtHead();
}

void ChainOfQueue::deleteAtHead()
{
	Node * tmpPtr = head.next;
	head.next = head.next->next;
	delete tmpPtr;
}

void ChainOfQueue::print()
{
	if (head.next == NULL)
	{
		cout << "队列为空!!!" << endl;
		return;
	}
	Node * p_head = head.next;
	while (p_head != NULL)
	{
		cout << p_head->data << " ";
		p_head = p_head->next;
	}
	cout << endl;
}

int main(void)
{
	ChainOfQueue queue;
	cout << "入队:" << endl;
	for (int i = 0; i < 10; i++)
	{
		queue.Enqueue(i);
		queue.print();
	}

	cout << "出队:" << endl;
	for (int i = 0; i < 10; i++)
	{
		queue.Dequeue();
		queue.print();
	}
	return 0;
}

 

全部评论

相关推荐

珩珺:那些经历都太大太空了,实习的情况不了解,大创项目连名字、背景、目的及意义都没体现出来;地摊经济更是看完连卖的什么产品都不知道,项目成果直接写营收多少都更直观真实一点;后面那个校文体部的更是工作内容是组织活动整理流程,成果变成了当志愿者,而且你们学校本科学生会大一入学就直接当部长吗,志愿里面还提到了疫情防控,全面解封是22年12月的事情,可能时间上也有冲突。可能你花了钱人家就用AI给你随便写了点内容改了一下,没什么体现个性化的点
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务