在 c++ 中对链表进行排序
Sorting a linked list in c++
我对无限循环感到生气,您认为合适的解决方案是什么?
void sorting () {
node * temphead = head;
node * tempnode = NULL;
for (int i=0; i<count; i++) {
for (int j=0; j<count-i; j++) {
if (temphead->data > temphead->next->data) {
tempnode = temphead;
temphead = temphead->next;
temphead->next = tempnode;
}
temphead=temphead->next;
count++;
}
}
}
我尝试增加计数并使用许多条件,在 for 循环之前和之后使用许多条件,但没有结果
滑动
链表的一种更简单的方法是这样的:
for (node *current = head; current != nullptr; current = current->next) {
// This will run through all of the nodes until we reach the end.
}
滑动到倒数第二项(确保node->next
存在)如下所示:
for (node *current = head; current->next != nullptr; current = current->next) {
// Go through all of the nodes that have a 'next' node.
}
如果要计算链表中有多少项,请执行如下操作:
int count = 0;
for (node *current = head; current != nullptr; current = current->next) {
count = count + 1;
}
因此,像上面这样的选择类型排序如下所示:
for (node *index = head; index->next != nullptr; index = index->next) {
for (node *selection = index->next; selection != nullptr; selection = selection->next) {
if (index->data > selection->data) {
swap(index->data, selection->data);
}
}
}
尽管对链表进行排序通常不是最好的方法(除非您正在执行合并)。
问题是您正在循环直到计数,并且在每次运行循环//删除行计数++以避免删除无限循环时都会增加计数
相关文章:
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 合并两个排序链表时运行时出错
- 在 C++ 中合并两个排序链表
- 在排序链表中插入结构并将其写入二进制文件
- C++:按数字排序链表错误
- 家庭作业的排序链表程序中的分段错误
- 删除已排序链表中的值
- 排序链表-移动节点还是交换数据成员
- 单排序链表-无限循环
- 插入排序链表c++
- 冒泡排序链表C++
- 将元素添加到排序链表C++时出现问题
- 升序排序 - 链表
- 气泡排序链表不排序
- C++ 中的排序链表不会插入
- 删除具有重复相同值的已排序链表中的重复值
- 未排序链表实现检查完毕
- 插入排序链表c++
- c++中从排序链表中删除重复值节点的方法
- 排序链表和addSorted函数问题