1. 程式人生 > >資料結構 鏈式佇列C/C++

資料結構 鏈式佇列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;
}