[英]Insertion Sort with a Singly Linked List in C++
我正在嘗試為我的 LinkedList 類編寫一個方法,該方法將按名稱對 Person 對象的鏈接列表進行排序。 我的方法編譯得很好,但是當我嘗試對人員列表進行排序時,輸出不正確。 它也永遠不會停止運行。 例如,這段代碼
Person *p1 = new Person("K", "B");
Person *p2 = new Person("A", "A");
Person *p3 = new Person("S", "M");
Person *p4 = new Person("B", "M");
LinkedList ll;
ll.insertFront(*p1);
ll.insertFront(*p2);
ll.insertFront(*p3);
LinkedList newList = ll.insertionSort();
newList.print();
cout << endl;
給出這個輸出
B, K
A, A
誰能幫我弄清楚我的算法哪里出了問題? 謝謝!
這是我用來按名字和姓氏排序名稱的方法:
int Person::compareName(Person p)
{
if (lName.compare(p.lName) > 0)
{
return 1;
}
else if (lName.compare(p.lName) == 0)
{
if (fName.compare(p.fName) > 0)
{
return 1;
}
else return -1;
}
else return -1;
}
插入排序方法:
LinkedList LinkedList::insertionSort()
{
//create the new list
LinkedList newList;
newList.front = front;
Node *n;
Node *current = front;
Node *trail = NULL;
for(n=front->link; n!= NULL; n = n->link)//cycle through old chain
{
Node* newNode = n;
//cycle through new, sorted chain to find insertion point
for(current = newList.front; current != NULL; current = current->link)
{
//needs to go in the front
if(current->per.compareName(n->per) < 0)
{
break;
}
else
{
trail = current;
}
}
//if it needs to be added to the front of the chain
if(current == front)
{
newNode->link = newList.front;
newList.front = newNode;
}
//else goes in middle or at the end
else{
newNode->link = current;
trail->link = newNode;
}
return newList;
}
您在內部 for 循環中有 current->link ,在 else 中有到內部 for 循環的鏈接。 我假設你真的在 for 循環中有 current = current->link 或者它什么都不做。 如果是這樣,您將跳過所有其他元素。
您還有語言方面的問題——您不是在創建新節點,而是在更改原始列表中的節點。 這意味着您在行走時正在更改列表,這會在您對其進行排序時破壞列表。 行為未定義,取決於您添加元素的順序。
即使您已經修復了任何鏈接列表處理問題(我沒有看過),您的compareName()
函數也有一個缺陷——當比較具有相同姓氏的Person
對象時,它可能會從函數返回而不提供值(在Name.compare(p.fName) <= 0
的情況下)。
從比較函數中獲得不確定的結果幾乎會破壞任何類型。
由於這可能是家庭作業,因此我將糾正問題作為練習。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.