【发布时间】:2016-11-05 21:16:54
【问题描述】:
我正在尝试使用以下代码在 C 中创建一个排序的链表,但在打印任何输入之前我遇到了分段错误。我相信这是因为我在我的 while 循环中检查了((*link)->value < val),但一开始它是NULL。如果列表中没有元素,我还尝试添加条件,但这不起作用。在没有 seg 的情况下,我如何检查要添加的值是否更小。有错吗?
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;
}
这里是打印列表:
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
【问题讨论】:
-
您需要更改 ||到&&
-
这只会输出 12 个值中最小的 4 个。输入为:72 19 47 31 8 36 12 88 15 75 51 29,列表打印为:8 12 15 29
标签: c linked-list