Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 按升序将节点插入到链接列表中_C_Insert_Linked List - Fatal编程技术网

C 按升序将节点插入到链接列表中

C 按升序将节点插入到链接列表中,c,insert,linked-list,C,Insert,Linked List,我有一个按升序排列的链表,在一些代码中,我将生成一个新节点并取出前两个节点,需要将其插入链表中的正确位置。我下面的代码正试图这样做,所以我应该得到打印语句,说列表现在有5个节点长列表现在有4个节点长列表现在有3个节点长等等 开始时,temp指向列表中的第一个节点。我的逻辑是,当它发现temp->next->frequency更大/相等时,它会将父节点->next指向temp->next(相等/更大的一个),并将temp->next指向父节点,从而将该节点插入列表。然而,这似乎不起作用 while

我有一个按升序排列的链表,在一些代码中,我将生成一个新节点并取出前两个节点,需要将其插入链表中的正确位置。我下面的代码正试图这样做,所以我应该得到打印语句,说
列表现在有5个节点长
列表现在有4个节点长
列表现在有3个节点长
等等

开始时,temp指向列表中的第一个节点。我的逻辑是,当它发现temp->next->frequency更大/相等时,它会将父节点->next指向temp->next(相等/更大的一个),并将temp->next指向父节点,从而将该节点插入列表。然而,这似乎不起作用

while (ind == 0)
{
    temp = temp -> next;
    if (temp -> next -> frequency >= parent_node -> frequency && temp != NULL)
    {
        parent_node -> next = temp -> next; /* parent points at bigger value */
        temp -> next = parent_node; /* temp points at parent */
        ind = 1;
    }
}

temp =  list -> start; /* point list back at start */
while (temp != NULL)
{
    temp = temp -> next; /* run through list */
    counter++;
    printf("The linked list is now: %d nodes long\n", counter);
}

它将打印列表,现在是1->10长,现在是1->9长,现在是1->8长。

代码“知道”temp和
temp->next
如何在
while(ind==0)下不
NULL
{temp=temp->next;
和下面的代码?呃,我假设它们只在列表末尾为NULL,而遍历它时它不是NULL?啊,我明白了。我添加了子句
&&temp!=NULL
,这修复了seg错误,但我想知道我的插入方法是否真的有效?当代码“似乎不工作”并且代码在引用之前,测试指针是防御性编码,有助于检测无效的假设。节省时间。考虑<代码>断言()/<代码> ID,这里还有一个问题需要解决吗?