附加到链接列表的末尾-C

时间:2020-11-08 12:42:46

标签: c linked-list

我试图从用户那里获取输入,将其存储到struct请求中,然后附加到作为参数获取的链表的末尾。到目前为止,这是我所拥有的,但我目前唯一看到的只是只有收到的输入,而没有所有先前的数据。我在这里做什么错了?

struct request *append(struct request *list){

    char f_name[NAME_LEN+1];
    char l_name[NAME_LEN+1];
    char e_address[EMAIL_LEN+1];
    char class_name[CLASS_LEN+1];

    //get input
    printf("Enter first name, last name, email adress, class name. ");
    scanf("%s %s %s %s", f_name, l_name, e_address, class_name);

    //allocate memory for the structure
    struct request* p = (struct request*) malloc(sizeof(struct request)); 
    struct request *temp = list;

    //store the data
    strcpy(p->first, f_name);
    strcpy(p->last, l_name);
    strcpy(p->email, e_address);
    strcpy(p->class, class_name);
    p->next = NULL; 

    //if list is empty return pointer to the newly created linked list
    if (list == NULL) {
       return p; 
    }

    //traverse to the end of the list and append the new list to the original list
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = p;


    return p;

}

0 个答案:

没有答案