我正在尝试按字母顺序对链接列表进行排序,但我的排序函数出现seg failure
。如何按字母顺序对列表进行排序。
typedef struct s_file
{
char *file_name;
struct s_file *next;
} t_file;
void sort_alpha(t_file **begin_list)
{
t_file *list;
char *tmp;
list = *begin_list;
if (list)
{
while (list)
{
if (strcmp(list->file_name, list->next->file_name) < 0)
{
tmp = list->file_name;
list->file_name = list->next->file_name;
list->next->file_name = tmp;
}
list = list->next;
}
}
}
最佳答案
在行
if (strcmp(list->file_name, list->next->file_name) < 0)
// list->next could be NULL so
// list->next->file_name could give seg fault
需要保护。可能的解决方案:
void sort_alpha(t_file **begin_list)
{
t_file *list;
char *tmp;
list = *begin_list;
if (list)
{
while (list && list->next)
{
if (strcmp(list->file_name, list->next->file_name) < 0)
{
tmp = list->file_name;
list->file_name = list->next->file_name;
list->next->file_name = tmp;
}
list = list->next;
}
}
}
关于c - 链表按字母顺序排序,c中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759093/