如何在C中创建一个新的头列表?

时间:2018-01-24 10:48:21

标签: c pointers struct

如何编写一个“add_first”函数,它将改变头并返回一个新变量的值而不改变“main”函数? 是否可以在不传递指针变量指针(双指针)的情况下执行此操作?

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

struct node_t
{
    int value;
    struct node_t *next;
};

int add_first(struct node_t *);
void print_list(struct node_t *);

int main(int argc, char **argv)
{
    struct node_t *head = NULL ;
    int rand_val = add_first(head);
    printf("Value =  %d\n", rand_val);
    print_list(head);
}

int add_first(struct node_t *lista)
{
    lista = (struct node_t*)malloc(sizeof(struct node_t));
    srand(time(NULL)); 
    int val = (int)(rand() / (RAND_MAX + 1.0) * 100.0);
    lista->value = 10;
    lista->next = NULL;
    return val;
}

void print_list(struct node_t * head) {
    struct node_t * current = head;

    while (current != NULL) {
        printf("%d\n", current->value);
        current = current->next;
    }
}

1 个答案:

答案 0 :(得分:2)

  

如何写一个&#34; add_first&#34;功能将改变头部并返回一个新变量的值,而不会在&#34; main&#34;功能

无法执行粗体部分,因为无法在不更改mainadd_first的情况下返回列表的头部。如果解除限制,有两种方法。第一种方法是将指针指向poointer到列表的头部。 add_first成为了这个:

int add_first(struct node_t **lista)
{
    newHead = (struct node_t*)malloc(sizeof(struct node_t));
    srand(time(NULL)); 
    int val = (int)(rand() / (RAND_MAX + 1.0) * 100.0);
    newHead->value = 10;
    newHead->next = *lista;
    *lista = newHead;
    return val;
}

main

int rand_val = add_first(&head);

它会创建一个新的列表头,将现有列表链接到其next,并将传入的列表设置为新头。

另一种方式只能假设您确实想要将新项目中的值设置为您要返回的值。在这种情况下,您可以返回列表的新头

(struct node_t *add_first(struct node_t *lista)
{
    newHead = (struct node_t*)malloc(sizeof(struct node_t));
    srand(time(NULL)); 
    newHead->value = (int)(rand() / (RAND_MAX + 1.0) * 100.0);
    newHead->next = lista;
    return newHead;
}

main

head = add_first(head);
rand_val = head->value;