Passing a linked list head through a function as address in C

▼魔方 西西 提交于 2019-12-03 21:17:32
nimrodm

You could pass a struct node** as suggested by @sje397.

However, I would suggest the following design (which, in my opinion is easier to reason about too):

/* returns the new head of the list */
struct node *insert (struct node* current_head, int x) {
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = current_head;
    return temp;
}

and use it like

head = insert(head, 5);

In this case I would also rename the function something like push_front.

Just for completeness, I think @sje397 meant something like the following (Typical linked list code rewritten again and again by every C programmer...):

void insert(struct node **head, int x) {
    struct node* new_head = (struct node*)malloc(sizeof(struct node));
    new_head->data = x;
    new_head->next = *head;

    *head = new_head;
}

In C there is no pass by reference.
Your insert function isn't inserting a node in the list, its just changing the node which the head points to. Because of temp->next = NULL the list will always contain two nodes.

Another error is that you're just modifying a local copy of the head node. To fix this You have 3 choices:

-You can make the head node global

-You can pass a pointer to the head node(pointer to pointer) to the function.

-You can return the modified head node by the function.

Redefine the insert function to:

void insert (struct node** rec, int x) {
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = NULL;
    *rec = temp; // head and rec is now pointing to the same node
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!