[英]C - Inserting into sorted linked list with double pointers
我正在尝试使用以下代码在C中创建一个排序的链表,但是在打印任何输入之前遇到了段错误。 我相信这是因为我正在while循环中检查((*link)->value < val)
,但一开始它是NULL
。 我还尝试为列表中没有元素的条件添加条件,但这没有用。 我如何才能检查要添加的值是否较小而不会出现段。 故障?
struct NodeTag {
int value;
struct NodeTag *next;
};
typedef struct NodeTag Node;
typedef struct {
Node *head;
int length;
} List;
void insertSorted(List *list, int val) {
Node **link = &(list->head);
while (*link != NULL || (*link)->value < val) {
//move node to correct place in list
link = &((*link)->next);
}
//create new node
Node *n = (Node *)malloc(sizeof(Node));
n->value = val;
//set next to null
n->next = NULL;
//insert new node
*link = n;
}
这是printList:
void printList(List *list) {
printf("%d elements :", list->length);
for (Node *n = list->head; n; n = n->next)
printf( " %d", n->value);
printf( "\n" );
}
输入: 72 19 47 31 8 36 12 88 15 75 51 29
预期输出: 8 12 15 19 29 31 36 47 51 72 75 88
这是您的代码中的一些问题:
您使用||
代替&&
。 如果next
成员为NULL
,则您位于列表的末尾,在此位置插入。
参数名称是list
但您在正文中使用link
您无需在C中malloc()
的返回值,这被认为会适得其反,特别是如果您忘记包含<stdlib.h>
。
您不测试分配失败
您没有将列表的其余部分链接到插入的节点。
该函数应该返回一个指向插入节点的指针,使调用者有机会检查内存分配失败。
您不应该评论显而易见的内容。
这是更正的版本:
#include <stdlib.h>
Node *insertSorted(List *list, int val) {
Node **link = &list->head;
while (*link != NULL && (*link)->value < val) {
//skip this node
link = &(*link)->next;
}
//create new node
Node *n = malloc(sizeof(Node));
if (n != NULL) {
n->value = val;
n->next = *link; // link the rest of the list
*link = n; //insert new node
}
return n;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.