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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40990854/article/details/82966652

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

下面给出小编写的顺序存储的链接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;
}

猜你喜欢

转载自blog.csdn.net/qq_40990854/article/details/82966652