【问题标题】:insert end linked list插入结束链表
【发布时间】:2015-05-21 20:29:33
【问题描述】:

我在链表末尾插入数据时遇到问题。我已经尝试了一切,但没有任何帮助。它只显示第一个和最后一个 no,但显示中间的数字。

以下是我的代码。

struct node
{
  int data;

  struct node *next;

} *start;

add()  
{

    int a,b,c=0;
    scanf("%d",&a);

    struct node *new,*new1;
    new=(struct node *)malloc(sizeof(struct node));
    new1=(struct node *)malloc(sizeof(struct node));
    while(a!=0)
    {
        c=a%10;
        a=a/10;
        if(start==NULL)
        {
            new->data=c;
            start=new;
            printf("%d\n",start->data);

        }
        else
        {
            new1->data=c;
            new->next=new1;
            new=new->next;

        }
    }
    new->next=NULL;
}

【问题讨论】:

标签: c linked-list


【解决方案1】:

您每次都在重写第二个节点。移动到链表的最后,然后添加

add()  
{

int a,b,c=0;
scanf("%d",&a);

struct node *new,*new1;
while(a!=0)
{
    c=a%10;
    a=a/10;

    new=(struct node *)malloc(sizeof(struct node));

    if(start==NULL)
    {
        new->data=c;
        new->next = NULL;
        start=new;
        printf("%d\n",new->data);

    }
    else
    {
        new1=(struct node *)malloc(sizeof(struct node));
        new1 = start;
        while(new1->next != NULL) {
            new1 = new1->next;
        }
        new->data=c;
        new->next = NULL;
        printf("%d\n",new->data);
    }
}
}

【讨论】:

  • 虽然我努力编译它。运行此代码,它应该可以工作。告诉我
  • else 仍然存在问题。 new1 被分配了两次。
  • 啊。我的错。看不出来。感谢您指出了这一点。在编译器上对其进行了测试。效果很好。
  • 可能想要更新您的答案,以便剪切/粘贴对其他人有用... :)
【解决方案2】:
void print(struct node *p){
    while(p){
        printf("%d\n", p->data);
        p = p->next;
    }
}

void add(void){
    int a;
    scanf("%d", &a);

    struct node *new, *curr;
    for( ;a!=0; a /= 10){
        new = (struct node *)malloc(sizeof(struct node));
        new->data = a % 10;
        new->next = NULL;

        if(start==NULL)
            start = curr = new;
        else
            curr = curr->next = new;
    }
    print(start);
}

【讨论】:

    【解决方案3】:

    解决了。问题是我一次又一次地使用相同的 new1。当令人满意的情况出现时,它应该总是被分配内存。修改后的代码如下:-

    int a,b,c=0;

    scanf("%d",&a);
    while(a!=0)
    {
        struct node *new,*new1;
        c=a%10;
        a=a/10;
        if(start==NULL)
        {
            new=(struct node *)malloc(sizeof(struct node));
            new->data=c;
            start=new;
            printf("%d\n",start->data);
        }
        else
        {
            new1=(struct node *)malloc(sizeof(struct node));
            new1->data=c;
            new->next=new1;
            printf("%d\n",new->next->data);
            new=new->next;
            new->next=NULL;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 2022-01-20
      • 2015-02-04
      • 1970-01-01
      • 2017-08-27
      相关资源
      最近更新 更多