1. 程式人生 > >(C++版)連結串列(二)——實現單項迴圈連結串列建立、插入、刪除等操作

(C++版)連結串列(二)——實現單項迴圈連結串列建立、插入、刪除等操作

        連結串列(二)單向迴圈連結串列的實現,下面實現程式碼:

#include <iostream>
#include <stdlib.h>
using namespace std;

//結點類
class Node {
public:
	int data;
	Node *pNext;
};
//單向迴圈連結串列類
class CircularLinkList {
public:
	CircularLinkList() {
		head = new Node;
		head->data = 0;
		head->pNext = head;
	}
	~CircularLinkList() {delete head;}
	void CreateLinkList(int n);				//建立單向迴圈連結串列
	void InsertNode(int position, int d);	//在指定位置插入結點
	void TraverseLinkList();				//遍歷連結串列
	bool IsEmpty();							//判斷連結串列是否為空
	int GetLength();						//得到連結串列的長度
	void DeleteNode(int position);			//刪除指定位置結點
	void DeleteLinkList();					//刪除連結串列
private:
	Node *head;
};

void CircularLinkList::CreateLinkList(int n) {
	if (n < 0) {
		cout << "輸入結點個數錯誤!" << endl;
		exit(EXIT_FAILURE);
	}
	else {
		Node *pnew, *ptemp = head;
		int i = n;
		while (n-- > 0) {
			cout << "輸入第" << i - n << "個結點值:";		
			pnew = new Node;
			cin >> pnew->data;
			pnew->pNext = head;
			ptemp->pNext = pnew;
			ptemp = pnew;	
		}	
	}
}

void CircularLinkList::InsertNode(int position, int d) {
	if (position < 0 || position > GetLength() + 1) {
		cout << "輸入位置錯誤!" << endl;
		exit(EXIT_FAILURE);
	}
	else {
		Node *pnew, *ptemp = head;
		pnew = new Node;
		pnew->data = d;
		while (position-- > 1)
			ptemp = ptemp->pNext;
		pnew->pNext = ptemp->pNext;
		ptemp->pNext = pnew;
	}
}

void CircularLinkList::TraverseLinkList() {
	Node *ptemp = head->pNext;
	while (ptemp != head) {
		cout << ptemp->data << " ";
		ptemp = ptemp->pNext;
	}
	cout << endl;
}

bool CircularLinkList::IsEmpty() {
	if (head->pNext == head)
		return true;
	else
		return false;
}

int CircularLinkList::GetLength() {
	int n = 0;
	Node *ptemp = head->pNext;
	while (ptemp != head) {
		n++;
		ptemp = ptemp->pNext;
	}
	return n;
}

void CircularLinkList::DeleteNode(int position) {
	if (position < 0 || position > GetLength()) {
		cout << "輸入位置錯誤!" << endl;
		exit(EXIT_FAILURE);
	}
	else {
		Node *ptemp = head, *pdelete;

		while (position-- > 1)
			ptemp = ptemp->pNext;
		pdelete = ptemp->pNext;
		ptemp->pNext = pdelete->pNext;
		delete pdelete;
		pdelete = NULL;
	}
}

void CircularLinkList::DeleteLinkList() {
	Node *pdelete = head->pNext, *ptemp;
	while (pdelete != head) {
		ptemp = pdelete->pNext;
		head->pNext = ptemp;
		delete pdelete;
		pdelete = ptemp;
	}
}

//測試函式
int main() {

	CircularLinkList cl;
	int position = 0, value = 0, n = 0;
	bool flag = false;

	cout << "請輸入需要建立單向迴圈連結串列的結點個數:";
	cin >> n;
	cl.CreateLinkList(n);

	cout << "列印連結串列值如下:";
	cl.TraverseLinkList();

	cout << "請輸入插入結點的位置和值:";
	cin >> position >> value;
	cl.InsertNode(position, value);
	
	cout << "列印連結串列值如下:";
	cl.TraverseLinkList();

	cout << "請輸入要刪除結點的位置:";
	cin >> position;
	cl.DeleteNode(position);

	cout << "列印連結串列值如下:";
	cl.TraverseLinkList();

	cl.DeleteLinkList();
	flag = cl.IsEmpty();
	if (flag)
		cout << "刪除連結串列成功!" << endl;
	else
		cout << "刪除連結串列失敗!" << endl;

	return 0;
}