Yugal Jindle
Yugal Jindle

Reputation: 45646

what wrong with this function to add element to a linked list?

Here is my code :

typedef struct node {
    int data;
    struct node *next;
} Node;

void add(Node *head, Node *node) {
    Node *ptr;
    ptr = head;
    if(head==NULL) {
        head=node;
    }
    else {
        while(ptr->next != NULL) {
            ptr = ptr->next;
        }
        ptr->next = node;
    }
}

Node* create(int a) {
    Node *node;
    node = (Node*)malloc(sizeof(Node));
    node->data = a;
    node->next = NULL;
    return node;
}

int main() {
    Node *head;
    head = NULL;
    int i;
    for(i=0; i<10; i++) {
        Node *node;
        node = create(i);
        add(head, node);
    }
}

Problem is : head is getting redefined in the function add, everytime add is called. why ?

Upvotes: 1

Views: 101

Answers (1)

Tom W
Tom W

Reputation: 1334

Because add is receiving a copy of your pointer when you call it. You set head in that function, but that changes the local copy, not other variable named head in main(). You would need to do something like this (I just put the lines to change; the rest look okay):

  void add(Node **head, Node *node) {
    *head = node;
  }



int main() {
    add(&head, node);
 }

Upvotes: 6

Related Questions