[英]C - Inserting into sorted linked list with double pointers
I'm trying to create a sorted linked list in C with the following code but I am getting a segmentation fault before any of my input is printed. 我正在尝试使用以下代码在C中创建一个排序的链表,但是在打印任何输入之前遇到了段错误。 I believe it is because I'm checking ((*link)->value < val)
in my while loop, but at the beginning, it is NULL
. 我相信这是因为我正在while循环中检查((*link)->value < val)
,但一开始它是NULL
。 I also tried adding a conditional for if there are no elements in the list but that didn't work. 我还尝试为列表中没有元素的条件添加条件,但这没有用。 How could I check to see if the value to add is smaller without getting seg. 我如何才能检查要添加的值是否较小而不会出现段。 fault? 故障?
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;
}
Here is printList: 这是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" );
}
Input: 72 19 47 31 8 36 12 88 15 75 51 29
输入: 72 19 47 31 8 36 12 88 15 75 51 29
Expected output: 8 12 15 19 29 31 36 47 51 72 75 88
预期输出: 8 12 15 19 29 31 36 47 51 72 75 88
Here are some problems in your code: 这是您的代码中的一些问题:
you use ||
您使用||
instead of &&
. 代替&&
。 If the next
member is NULL
, you are at the end of the list, insert right there. 如果next
成员为NULL
,则您位于列表的末尾,在此位置插入。
the argument name is list
but you use link
in the body 参数名称是list
但您在正文中使用link
you don't need to cast the return value of malloc()
in C and it is considered counterproductive, especially if you forget to include <stdlib.h>
. 您无需在C中malloc()
的返回值,这被认为会适得其反,特别是如果您忘记包含<stdlib.h>
。
you do not test for allocation failure 您不测试分配失败
you do not link the rest of the list to the inserted node. 您没有将列表的其余部分链接到插入的节点。
the function should return a pointer to the inserted node, giving the caller a chance to check for memory allocation failure. 该函数应该返回一个指向插入节点的指针,使调用者有机会检查内存分配失败。
you should not comment the obvious. 您不应该评论显而易见的内容。
Here is a corrected version: 这是更正的版本:
#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.