插入结束链表

时间:2015-05-21 20:29:33

标签: c linked-list

我在链表末尾插入数据时遇到问题。我已经尝试了一切但没有帮助。它只显示第一个和最后一个,但是数字介于两者之间。

以下是我的代码。

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;
}

3 个答案:

答案 0 :(得分:0)

你每次都在重写第二个节点。移到链接列表的最后一个,然后添加

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);
    }
}
}

答案 1 :(得分:0)

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);
}

答案 2 :(得分:0)

解决了它。问题是我一次又一次地使用相同的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;
    }
}
相关问题