【发布时间】:2014-04-19 06:30:55
【问题描述】:
我制作了一个函数,可以在保留列表的同时将节点插入到链表中。但是,在插入 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 语句甚至 else 语句并再次运行。
-
计算机不会忽略“if”语句。检查为什么你的条件不是你所期望的。
-
我确实检查了它们。我什至添加了 else 语句,这样它就会打破循环。但事实并非如此。在 GDB 中,程序确实超出了 else if 语句的行,我从来没有看到 else 语句然后函数再次运行。
-
尝试将 printf 语句放在您关心的每个“if”和“else”中。确保您在没有优化(没有 -O 或 -O2 或类似的东西)和调试符号(使用 -g)的情况下进行编译。我向你保证,除非条件为假,否则程序不会“越过”你的 if 块。
标签: c sorting linked-list infinite-loop