在C中按升序排序链表
我正在为我的C编程课程编写一个程序,它应该给我们使用链表的经验。作业的最后一部分要求我们获取一个链表,并使用我们之前在程序中编写的prepend或append函数按升序对其进行排序在C中按升序排序链表,c,sorting,linked-list,C,Sorting,Linked List,我正在为我的C编程课程编写一个程序,它应该给我们使用链表的经验。作业的最后一部分要求我们获取一个链表,并使用我们之前在程序中编写的prepend或append函数按升序对其进行排序 struct lnode { int datum; struct lnode *next; }; struct lnode* prepend(struct lnode *list, int x) { struct lnode *node = (struct lnode *)malloc(sizeof(
struct lnode
{
int datum;
struct lnode *next;
};
struct lnode*
prepend(struct lnode *list, int x)
{
struct lnode *node = (struct lnode *)malloc(sizeof(struct lnode));
node -> datum = x;
node -> next = list;
list = node;
return list;
}
struct lnode*
append(struct lnode *list, int x)
{
if(list==NULL){
list = (struct lnode *)malloc(sizeof(struct lnode));
list -> datum = x;
list -> next = NULL;
}else{
list -> next = append(list->next,x);li
}
return list;
}
上面是我们在类中设计的append和prepend函数
下面是我们在课堂上制作的删除功能:
struct lnode*
delete(struct lnode *list, int x)
{
struct lnode* tmp;
if(list == NULL){
return list;
}else if(list-> datum == x){
tmp = list -> next;
list -> next = NULL;
free(list);
list = tmp;
return list;
}else{
list->next = delete(list->next,x);
return list;
}
}
int
find_smallest(struct lnode*list)
{
int smallest;
smallest = list->datum;
while(list!=NULL){
if(list->datum < smallest){
smallest = list->datum;
}
list = list->next;
}
return smallest;
}
我遇到的问题是,我似乎得到了一个无限循环。
我运行了一个测试用例,在每次运行循环之后,我都会打印列表的元素,其中列表最初是5 4 1 2 3,打印出来的内容是5 4 2 3,反复打印,直到我强制程序停止。因此,我认为它只正确运行了一次?变量
new\u list
未在sort
函数中初始化。append
函数随后错误地附加到不存在的节点
改变
struct lnode *new_list;
到
在
排序
函数中。你也可以发布你的delete()
函数吗?也许你应该发布代码评论,或者在ideone或任何其他在线编辑器上提供完整代码的链接。其他人可能很容易发现错误way@sashacodereview.stackexchange.com仅适用于已按预期工作的代码。这是离题的。另外,始终建议读取不强制转换malloc返回值。为什么不在这里?@SimonAndréForsberg噢。很抱歉。我会记住这一点。谢谢
struct lnode *new_list;
struct lnode *new_list = NULL;