c-链表:插入一个名字和身份证号码到列表中



需要在列表中插入名称和id号的帮助。尝试时崩溃添加到列表中的号码

struct node {
int id;
char name[50];
struct node *next;
} *head;

struct node *insert(struct node * list, char nam[50], int id){
struct node *helper;
struct node *pNew;
pNew=(struct node*)malloc(sizeof(struct node));
strcpy(pNew->name, nam);
pNew->id = id;
pNew->next=NULL;
helper=list;
if (list == NULL)
    return pNew;
while (helper->next!=NULL)
    helper=helper->next;
helper->next=pNew;

return list;

}

int main()
{
char nameInsert[50];
char nameDelete[50];
int idNum, i;
struct node *n=NULL;
//beginning of linked list, must initialize
head = NULL;
//read in data using file input function
readDataFile();
//display data operations using while loop
while(1)
{
    printf("nData Operationsn");
    printf("n--------------n");
    printf("1. Insert Namen");
    printf("2. Display Namesn");
    printf("3. Delete by ID Numbern");
    printf("4. Delete by Namen");
    printf("5. Exitn");
    printf("Please enter a command: ");
    if(scanf("%d", &i) <= 0)
    {
        printf("Not valid input, please use integers 1 - 5");
        exit(0);
    }
    else
    {
        //beginning of switch case
        switch(i)
        {
            case 1:
                printf("Enter the name you would like to insert: ");
                scanf("%s",nameInsert);
                printf("Enter the ID number associated with the name: ");
                scanf("%d", &idNum);
                insert(n,nameInsert, idNum); //insert function
                break;

读取数据文件并将数据存储为链表的应用程序。提示用户输入学生的姓名提示用户输入用户的id号用数据填充链表节点的实例将新节点添加到现有链表

我已经简化并修改了您的insert()函数

struct node *insert(struct node * list, char *nam, int id){
    struct node *pNew;
    pNew=malloc(sizeof(struct node));
    if (pNew == NULL) {
        printf ("Unable to allocate memoryn")
        exit (1);
    }
    strncpy(pNew->name, nam, 49);       // limit the string copy length
    pNew->name[49] = 0;                 // precautionary terminator
    pNew->id = id;
    pNew->next = list;                  // point to list passed
    return pNew;                        // return new list
}

调用insert()的方式会忽略它的返回值,即新的列表头/根。

n = insert(n, nameInsert, idNum);   // use the return value

最新更新