C++按升序对链表进行排序
C++ sort linked list in ascending order
这是我的代码。我想知道为什么它不起作用。
sll_node *sortList(sll_node *head)
{
int temp=head->value;
if(head!=NULL||temp>head->next->value)
{
head->value=head->next->value;
head->next->value=temp;
}
else
{
sortList(head->next);
sortList(head->next->next);
sortList(head->next);
}
return head;
}
您展示的代码中的主要问题是您在知道指针是否有效之前就使用了指针。
因此,在将 temp 分配给 head-> 值或使用 head->next 之前,必须确保 head 不等于 NULL。在使用 head->next-> 值或 head->next-next> 之前,必须确保 head->next 不等于 NULL。
试试这个:
sll_node *sortList(sll_node *head)
{
if(head != NULL)
{
int temp=head->value;
if (head->next != NULL)
{
if (temp > head->next->value)
{
head->value=head->next->value;
head->next->value=temp;
}
else
{
sortList(head->next);
}
}
}
return head;
}
运行此程序后,您会遇到另一个问题。
如果您的列表是:[3, 2, 1, 4]
第一次传递排序列表将产生:[2, 3, 1, 4]
第二遍将产生:[2, 1, 3, 4]
第三遍也是最后一遍将产生:[2, 1, 3, 4]
我会让你尝试解决下一步。如果你有具体的问题,一旦你付出更多的努力,我会回答它们。
相关文章:
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 合并两个排序链表时运行时出错
- 在 C++ 中合并两个排序链表
- 在排序链表中插入结构并将其写入二进制文件
- C++:按数字排序链表错误
- 家庭作业的排序链表程序中的分段错误
- 删除已排序链表中的值
- 排序链表-移动节点还是交换数据成员
- 单排序链表-无限循环
- 插入排序链表c++
- 冒泡排序链表C++
- 将元素添加到排序链表C++时出现问题
- 升序排序 - 链表
- 气泡排序链表不排序
- C++ 中的排序链表不会插入
- 删除具有重复相同值的已排序链表中的重复值
- 未排序链表实现检查完毕
- 插入排序链表c++
- c++中从排序链表中删除重复值节点的方法
- 排序链表和addSorted函数问题