用C++中的单链表进行插入排序
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
的情况下)。
从比较函数中得到一个不确定的结果几乎会破坏任何类型的结果
既然这可能是家庭作业,我就把批改这道题当作练习。
相关文章:
- 链表c++插入,所有情况都已检查,但没有任何工作
- 对单向链表进行排序时出现运行时错误
- 按升序对链表进行排序
- C++ 双向链表 - 插入同时保持递增顺序
- C++ 链表合并排序的实现在连接 1 个以上节点的子列表时失败
- 程序 使用链表插入数据时停止工作
- 链表插入和打印C++
- 对双向链表进行排序会产生运行时错误
- 在插入过程中对链表进行排序
- 双向链表插入方法实现 - 正在搜索哪个节点
- 链表插入(核心转储)
- 链表插入
- 如何改进单向链表插入函数 - C++
- 尝试对链表进行排序时跳过节点
- C++ 链表 - 插入节点函数不会更新函数范围之外的值
- 在C++中对int的链表进行排序
- C++ - 链表插入排序(字符串元素)
- 插入节点时对链表进行排序
- 链表插入、删除、排序
- 链表插入排序和减少多项式c++