如何编写一个“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;
}
}
答案 0 :(得分:2)
如何写一个&#34; add_first&#34;功能将改变头部并返回一个新变量的值,而不会在&#34; main&#34;功能强>
无法执行粗体部分,因为无法在不更改main
和add_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;