【发布时间】:2013-02-15 20:16:08
【问题描述】:
我正在尝试为我的 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;
}
【问题讨论】:
-
标题调整;虽然我还没有查看详细信息,但我怀疑这将是一个算法问题而不是语言问题,所以我不确定它那有多大关系。
-
您尝试过调试吗?换句话说,你有没有单步调试过代码,看看它在做什么?
-
天啊。当我阅读您的代码时,我很想为您编写它,而不是试图理解您在这里做什么。那会更快更容易。你的代码刚刚烤了我的面条。您的
compareName方法不正确,但它为提供的示例提供了正确的结果,因此问题不存在。请从旧列表中分离一个元素并将其附加到正确位置的新元素,而不是尝试重新链接列表中的断开链接。嗯,这就是我认为你正在做的事情,但我不能确定。
标签: c++ linked-list insertion-sort