如何在单个链表的开头添加节点?

时间:2014-06-15 12:47:05

标签: c data-structures singly-linked-list

我是编程世界的新手 我已经编写了使用单个链表开始添加数据的代码,我的代码没有按预期工作。我没有收到任何警告或错误。

我无法打印从用户处获取的数据,请帮我修复。

我的代码是:

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

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

void begin(struct st**);
void display(struct st*);

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

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

void display(struct st *ptr)
{
    while(ptr)  
    {

        printf("%s\t %d\n",ptr->name,ptr->roll); //Here its not printing as I expected                                                       
        ptr=ptr->next;
    }
}

2 个答案:

答案 0 :(得分:3)

begin函数不会将headptr设置为指向某个东西。要么你错了,要么你需要阅读列表操作。

您需要更改

temp->next=*ptr;
temp=*ptr;

*ptr = temp;

一开始。然后,您可以设置下一个节点。

答案 1 :(得分:1)

请尝试自己解决这些问题,在发布之前进行研究

   *ptr=temp; instead u did
    temp=*ptr//What does this means its make no sense please study the basic things before trying for linked list.