【问题标题】:Program Freezes When Inserting A New Node To A Linked List将新节点插入链接列表时程序冻结
【发布时间】: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


【解决方案1】:

您需要处理您要添加的条目需要位于列表头部的情况。现在你只在列表为空时添加到头部。这可以通过如下更改 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
    }
}

【讨论】:

  • 谢谢。好像我的逻辑有点不对劲。我需要检查何时添加到列表的头部,然后在结束之间。非常感谢您的澄清,代码有效。
猜你喜欢
  • 2016-03-30
  • 1970-01-01
  • 2021-02-25
  • 2013-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-05
  • 1970-01-01
相关资源
最近更新 更多