gpt4 book ai didi

c - 向链表添加节点时出现段错误

转载 作者:行者123 更新时间:2023-11-30 19:43:19 24 4
gpt4 key购买 nike

Node *orderedInsert(Node *p, int newval)
/* Allocates a new Node with data value newval
and inserts into the ordered list with
first node pointer p in such a way that the
data values in the modified list are in
ascending order as the list is traversed.
*/
{
Node* current = NULL;
Node* prev = NULL;
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->next = NULL;
newNode->data = newval;

if(newNode == NULL)
printf("Could not allocate memory for new node");

current = p;

if(p == NULL){

p = newNode;
newNode->next = NULL;
newNode->data = newval;
return p;
}
else if(newval < p->data){
newNode->next = p;
p = newNode;
return p;
}
else{
prev = p;
current = current->next;



while(newNode->data > current->data && current != NULL){

prev = current;
current = current->next;
}
if(prev->next == NULL){//the error is located somewhere here I think
prev->next = newNode;
newNode->data = newval;
newNode->next = NULL;
return p;
}
else{
newNode->next = current;
prev->next = newNode;
return p;
}
}
}

只有在添加比任何其他节点都大的节点时(意味着它将位于列表的末尾),我才会收到段错误错误。如果我按照 4 3 2 1 或 4 2 1 3 的顺序输入它们就可以了,但如果我按照 1 2 的顺序输入就不行了。

最佳答案

使用 1 和 2 相加的示例。

第一次迭代将会命中

if(p == NULL){
p = newNode;
newNode->next = NULL;
newNode->data = newval;
return p;
}

然后next指针指向NULL。

然后当你添加 2 时,你会看到:

else{ 
prev = p;
current = current->next;

while(newNode->data > current->data && current != NULL){
...
}

此处当前->下一个为NULL。将其分配给current后,current为NULL。

关于c - 向链表添加节点时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29738243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com