Node *head和Node **head有什么区别?

您所在的位置:网站首页 move什么意 Node *head和Node **head有什么区别?

Node *head和Node **head有什么区别?

2024-01-15 20:21| 来源: 网络整理| 查看: 265

在第一个函数头中,*head是指向分配在内存中某处的节点对象的指针:

void middle(struct Node *head); _____________________ | | *head --> | Node object | | [val=1][*next=NULL] | |_____________________|

而在第二个函数头中,**head_ref是指向内存中某个节点对象的指针:

void push(struct Node** head_ref, int new_data); _____________________ | | *head --> | Node object | ^ | [val=1][*next=NULL] | | |_____________________| | **head_ref

这是另一个间接层。为什么第二个构造是必要的?好吧,如果我想修改在我的函数作用域之外分配的东西,我需要一个指向它的内存位置的指针。在第一个示例中,我可以(使用head->)取消对*head指针的引用,以访问内存中的底层Node对象,并对其进行修改或访问其属性。

如果我想把一个新的Node对象推到列表的前面,使它成为新的头部,我需要修改head指针本身。就像我想用指针操作Node对象一样,现在我需要一个指向*head的指针(它只是碰巧是一个指针,而不是Node对象)才能修改它。

下面是push和一个之前/之后函数调用的内容:

void push(struct Node** head_ref, int new_data) { Node *new_head = malloc(sizeof(Node)); // allocate memory for the new head node new_head->data = new_data; // set its value new_head->next = *head_ref; // make it point to the // old head pointer *head_ref = new_head; // make it the new head by modifying // the old head pointer directly }/* Before push */ _____________________ | | *head --> | Node object | ^ | [val=1][*next=NULL] | | |_____________________| | **head_ref/* After calling push(&head, 2); * ^ * `&` operator gets the memory address of `head`, * which is a pointer. */ _________________ _____________________ | | | | *head --> | Node object | | Node object | ^ | [val=2] [*next]----->| [val=1][*next=NULL] | | |_________________| |_____________________| | **head_ref

下面是一个完整的示例:

#include #include typedef struct Node { int data; struct Node *next; } Node; void push(Node** head_ref, int new_data) { Node *new_head = malloc(sizeof(Node)); new_head->data = new_data; new_head->next = *head_ref; *head_ref = new_head; } void print(Node *head) { while (head) { printf("%d->", head->data); head = head->next; } puts("NULL"); } void free_list(Node *head) { while (head) { Node *tmp = head; head = head->next; free(tmp); } } int main() { Node *head = malloc(sizeof(Node)); head->next = NULL; head->data = 1; printf("Before push:\n"); print(head); push(&head, 2); printf("\nAfter push:\n"); print(head); free_list(head); return 0; }

输出:

Before push: 1->NULL After push: 2->1->NULL


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3