【发布时间】:2020-03-26 18:26:19
【问题描述】:
我一直在为一个学校项目工作,遇到了这个问题。
我正在尝试使用 malloc 存储列表,但这段代码似乎不起作用。
column_t *sorted_insert(column_t *lst, char col3[MAX_SIZE], long int rep){
if (!lst || rep < lst->rep)
{
column_t *new = (column_t*) malloc(sizeof(column_t));
strcpy(new->col3, col3);
new->rep = rep;
new->next = lst;
new->previous = NULL;
lst = new;
if (lst->next)
lst->next->previous = new;
}else
{
lst->next = sorted_insert(lst->next,col3,rep);
lst->next->previous = lst;
}
return lst;
}
尝试调用函数:
sorted_insert(lst,"Test",0);
printf("%s",lst->col3);
而且没有输出。程序刚刚关闭。
从莫斯科更新@Vlad
column_t *sorted_insert(column_t *lst, char col3[MAX_SIZE], long int rep){
if (lst == NULL|| rep < lst->rep)
{
column_t *new = malloc(sizeof(column_t));
if (new != NULL)
{
strcpy(new->col3, col3);
new->rep = rep;
new->previous = NULL;
new->next = lst;
if (lst != NULL)
lst->previous = new;
}
lst = new;
}else
{
column_t *new = sorted_insert(lst->next, col3, rep);
if (new != NULL)
{
lst->next = new;
new->previous = lst;
}
}
return lst;
}
将调用改为:
lst = sorted_insert(lst,tmp->col3,w);
display(lst);
输出:
列表的输出现在是正确的,但不是按升序排序的..
【问题讨论】:
-
不应该是 if 中的
&&而不是||? -
"这段代码似乎不起作用" 怎么回事?是什么让你这么想的?您尝试调试什么?请提供minimal reproducible example。
-
已更新。抱歉弄错了。
-
@Eraklon 如果列表为空或小于我认为的值..
-
rep的[目的]是什么?它没有改变。它是如何确定的?通常,您会根据strcmp在col和lst->col之间插入,但您的代码似乎使用rep作为排序标准。
标签: c sorting linked-list insert doubly-linked-list