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;
}
然后下一个指针指向NULL。
然后,当您添加2时,将命中:
else{
prev = p;
current = current->next;
while(newNode->data > current->data && current != NULL){
...
}
这current->next
是NULL。将其分配给后current
,current
为NULL。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句