我创建了一个函数,可以在保留列表的同时将节点插入到链接列表中。但是,插入 2 个元素后,如果下一个元素高于所有其他元素,则程序似乎无限循环。我的条件显示允许程序在发生某些情况时打破循环,但事实并非如此;
这是函数。请注意,head 是指向列表中第一个元素的指针,如果列表为空,则为 NULL:
//defines the node structure
typedef struct node{
int n;
struct node* next;
}node;
bool insert_node(int value)
{
int t=0;
//If list is empty
if (head==NULL){
node* first = malloc(sizeof(node));
//error checking
if (first==NULL)
return false;
head = first;
first->n=value;
first->next=NULL;
t=1;
}
else{
node* body=malloc(sizeof(node));
if (body==NULL){
t=9;
return false;
}
body->n=value;
node* ptr=head;
node*pre=head;
//putting new node into list
while(t==0){
//error checking
if (ptr==NULL)
break;
//insertion
else if (value<=ptr->n||ptr->next==NULL){
body->next=ptr;
pre->next=body;
t=1;
}
//next node
else if(value>ptr->n){
pre=ptr;
ptr=ptr->next;
}
//If all goes wrong
else
t=9; //breaks loop
}
}
if (t==1)
return true;
return false;
}
最佳答案
您需要处理这样的情况:您要添加的条目需要位于列表的开头。现在,您只能在列表为空时添加到头部。这是通过更改 if 来处理的,如下所示:
if (head==NULL || value < head->n){
node* first = malloc(sizeof(node));
//error checking
if (first==NULL)
return false;
first->next=head;
first->n=value;
head = first;
t=1;
}
既然已经处理了列表开头的添加,则需要更改 else 以使 pre 和 ptr 正确初始化,并且需要更改插入条件,如下所示:
node* ptr=head->next;
node* pre=head;
//putting new node into list
while(t==0){
//insertion
if (ptr==NULL || value<=ptr->n){
body->next=ptr;
pre->next=body;
t=1;
}
//next node
else if(value>ptr->n){
pre=ptr;
ptr=ptr->next;
}
//If all goes wrong
else
t=9; //breaks loop
}
}
关于c - 向链表插入新节点时程序卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23166764/