Write a C function to add a node to the end of a linked list
Write a C++ function to add a node to the end of a linked list. The function takes two arguments - the head of the linked list and the value to be added. It should return the head of the linked list. node \" AddNode(node \'head, int key); The linked list structure: struct node {Int key; node \"next;}; \" You can assume that the head being passed is initialized as follow node \"head = NULL;
Solution
node * AddNode(node * head, int key){
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = key;
temp->next = NULL;
if(head==NULL)
head = temp;
else{
curr = head;
while(curr->next!=NULL){
curr = curr->next;
}
curr->next = temp;
}
return head;
}
Thanks, let me know if there is any concern.
