c-程序在将新节点插入链表时冻结



我制作了一个函数,在保留列表的同时,将节点插入到链表中。然而,在插入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;
}

现在,添加到列表开头的操作已经完成,其他操作需要更改以正确初始化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
    }
}

最新更新