将节点添加到链表时出现分段错误
Segmentation fault when adding node to linked list
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){
...
}
此处current->next
为NULL。赋值给current
后,current
为NULL。
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){
...
}
此处current->next
为NULL。赋值给current
后,current
为NULL。