佇列的鏈式儲存結構的實現

丶di發表於2020-12-03

資料結構實驗一

3、佇列的鏈式儲存結構的實現
(1) 用隨機函式生成10個3位整數(100~999),把這些整數應用入隊操作存於佇列中;
(2) 應用遍歷操作輸出佇列的內容;
(3) 把佇列的內容翻轉,應用出隊操作輸出佇列的內容。

#include<iomanip>
#include<stdio.h>
#include<iostream>
using namespace std;
struct QueueNode {
public:
	int data;
	QueueNode() { this->next = NULL; }
	QueueNode* next;
	
};
struct Queue {
public:
	QueueNode* begin, * end;  //設定頭指標begin,尾指標end,左開右閉,移動end指標儲存資料
	Queue() {
		//定義建構函式,初始化指標begin,尾指標end
		begin = new QueueNode; 
		end = begin;
		end->next = NULL;
	}
	//返回第一個節點的資料
	int front() {
		return begin->next->data;
	}
	//返回最後一個節點的資料
	int back() {
		return end->data;
	}
	//判斷佇列是否為空,由於初始化時,從首指標begin的下一個節點開始儲存資料,只需判斷頭尾是否相等就可以判斷是否為空
	bool isEmpty() {
		return begin==end? 1 : 0;
	}
	//往佇列中新增新節點資料
	void push(int data) {
		QueueNode* tempNode = new QueueNode();
		tempNode->data = data;
		end->next = tempNode;
		end = tempNode;
		end->next = NULL;
	}
	//彈出佇列首個節點
	int pop() {
		if (isEmpty())return -1;
		QueueNode* tempNode = this->begin->next;
		//移動佇列中第一個有效的節點位置
		this->begin->next = this->begin->next->next;
		//判斷該節點是否是唯一個的節點,若是則彈出後佇列為空,尾指標end=頭指標begin
		if (tempNode == this->end) this->end = this->begin;
		return tempNode->data;
	}
	//應用遍歷操作輸出佇列的內容;
	void show() {
		QueueNode* tempNode = this->begin->next;
		while (tempNode!=NULL) {
			cout << tempNode->data << " ";
			tempNode = tempNode->next;
		}
		cout << endl;
	}
	//用隨機函式生成10個3位整數(100~999),把這些整數應用入隊操作存於佇列中;
	void RandInit() {
		for (int i = 0; i < 10; i++) {
			int number = rand() % 900 + 100;
			this->push(number);
			cout << number << " ";
		}
		cout << endl;
	}
	//把佇列的內容翻轉,應用出隊操作輸出佇列的內容。
	void reverse() {
		if (this->begin->next == NULL)return;
		if (this->begin->next->next == NULL) {
			cout << this->begin->next->data << endl; return;
		}
		end = begin->next;
		QueueNode* tempNode, * l = this->begin->next, * r = l->next;
		for (; r != NULL; r = tempNode) {
			tempNode = r->next;
			r->next = l;
			l = r;
		}
		begin->next->next = NULL;
		begin->next = l;
		show();
	}
};
int main() {
	Queue* queue = new Queue(); 
	//queue->begin->next = queue->end->next = NULL;
	cout << "輸出隨機建立的佇列:" << endl;
	queue->RandInit();
	cout << "輸出佇列的首元素:" << endl;
	cout << queue->front() << endl;
	cout << "輸出佇列的尾元素:" << endl;
	cout << queue->back() << endl;

	cout << "輸出翻轉後的佇列:" << endl;
	queue->reverse();
	cout << "輸出佇列翻轉後的首元素:" << endl;
	cout << queue->front() << endl;
	cout << "輸出佇列翻轉後的尾元素:" << endl;
	cout << queue->back() << endl;
}

相關文章