1. 程式人生 > >(頭冷)番外篇——迴圈連結串列的遍歷(補)

(頭冷)番外篇——迴圈連結串列的遍歷(補)

上次的教程中缺少了對迴圈連結串列的遍歷操作。今天特意來補上。迴圈連結串列的特點就是可以通過連結串列中的任一元素訪問到另一個元素。 實現的思路是這樣的,我們要定義兩個函式。一個函式負責通過元素匹配找到開始的新的尋找的結點,返回值為CircularNode * 型,另一個函式負責列印結果,通過結點的順序來列印新的迴圈連結串列的順序。好啦,我們來實現一下。

1.宣告兩個函式

在之前的CircelLinkList.h裡宣告兩個函式

/**訪問迴圈元素通過元素返回結點
 *引數1:需要操作的迴圈連結串列
 *引數2:需要查詢的元素
 */
CircularNode* GetCircularLinkListNode(CircularLinkList * cList, DataType element);

/**根據迴圈連結串列的結點開始列印
 *引數1:需要列印的迴圈連結串列
 *引數2:開始列印的結點
 */
void PrintCircularListByNode(CircularLinkList * cList, CircularNode * node);

2.實現主要演算法

在CircleLinkList.cpp裡實現剛才定義的兩個函式

/**訪問迴圈元素通過元素返回結點
 *引數1:需要操作的迴圈連結串列
 *引數2:需要查詢的元素
 */
CircularNode* GetCircularLinkListNode(CircularLinkList * cList, DataType element)
{
	CircularNode * node = cList->next;
	if (!node)
	{
		cout << "無法找到結點" << endl;
		return NULL;
	}
		
	do
	{
		if (node->data.id == element.id && (strcmp(node->data.name, element.name) == 0))
			return node;
		node = node->next;
	} while (node != cList->next);

}

/**根據迴圈連結串列的結點開始列印
 *引數1:需要列印的迴圈連結串列
 *引數2:開始列印的結點
 */
void PrintCircularListByNode(CircularLinkList * cList, CircularNode * node)
{
	if (!node)
	{
		cout << "無法找到結點,無法列印!!" << endl;
		return;
	}
	CircularNode *  origNode = node;
	do {
		cout << node->data.id << "\t" << node->data.name << endl;
		node = node->next;
	} while (node != origNode);

}

3.最後的測試程式碼

void TestCircularList()
{
	CircularLinkList * cList = new CircularLinkList;
	cList->length = 0;
	cList->next = NULL;
	InitCircleList(cList, dataElements, 5);
	PrintCircleList(cList);
	DataType insData = {9, "小象"};
	InsertCircleList(cList, 6, insData);
	PrintCircleList(cList);
	DeleteCircularElem(cList, 3);
	PrintCircleList(cList);
	DataType elem = {4, "小狗"};
	CircularNode * startNode = GetCircularLinkListNode(cList, elem);
	PrintCircularListByNode(cList, startNode);
}