【问题标题】:Adding a node containing multi-digit number at the nth position in a linked list在链表的第n个位置添加一个包含多位数字的节点
【发布时间】:2014-08-06 11:09:44
【问题描述】:

我已经编写了用于在第 n 个位置插入节点的代码。
当用户在节点中输入 1 位数字时,它可以正常工作,但是当用户输入等于或超过两位数字时,它只会在无限循环中继续打印最后一个节点。

我不知道出了什么问题。我的代码在下面

#include<stdio.h>
#include<stdlib.h>

struct st
{
    int roll;
    char name[20];
    struct st *next;
};

void add_middle(struct st **ptr)
{
    struct st *temp,*temp1;
    temp=malloc(sizeof(struct st ));
    printf("netre ur name\n");
    scanf("%s",temp->name);
    printf("enter ur roll\n");
    scanf("%d",&(temp->roll));

    if((*ptr==NULL)||(temp->roll<(*ptr)->roll))
    {
        temp->next=*ptr;
        *ptr=temp;
    }
    else
    {
        temp1=*ptr;
        while(temp1)
        {
            if((temp1->next==NULL)||(temp1->next->roll>temp->roll))
            {
                temp1->next=temp;
                temp->next=temp1->next;
                break;
            }
            temp1=temp1->next;
        }

    }
}

void display(struct st *ptr)
{
    while(ptr)
    {
        printf("%s %d\n",ptr->name,ptr->roll);
        ptr=ptr->next;
    }
}

main()
{
    struct st *headptr=0;
    add_middle(&headptr);`
        add_middle(&headptr);
    add_middle(&headptr);
    display(headptr);
}

【问题讨论】:

  • 我假设您的代码中有错误:add_middle(&amp;headptr);`?请注意该行末尾的`
  • 尽管缺少输入验证,但如果您利用该指针对指针的最佳表现,您可以让自己更轻松; see example。无论如何,祝你好运。
  • 我希望代码从头部开始查看每个现有节点,如果没有节点,将现有节点与新节点进行比较,否则仅将现有 code.next 与 ptr 更新到新节点和新节点.next = null。如果新节点大于现有节点,则更新 2 个下一个指针(现有节点到新节点和新节点到先前现有节点。作为建议,像 temp 和 temp1 这样的名称非常令人困惑。最好以与其相关的方式命名它们实际内容。

标签: c data-structures linked-list dynamic-memory-allocation


【解决方案1】:

让我们看看插入新节点时会发生什么:

temp1->next = temp;
temp->next = temp1->next;

这将使之前的节点(temp1)指向新的节点,这很好。然后它将让新节点 (temp) 指向自身 (temp1-&gt;next == temp),这很糟糕。

要解决此问题,您只需交换这两行即可。那就是:

if ((temp1->next==NULL) || (temp1->next->roll > temp->roll)) {
    temp->next = temp1->next;
    temp1->next = temp;
    break;
}

此外,如果您使用更好的变量名,这可能会更清楚:

  • temp1 变为 previousNode
  • temp 变为 newNode

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2020-11-17
    相关资源
    最近更新 更多