BOTJr. BOTJr. - 3 months ago 20
C Question

Node Insertion,Linked Lists

I have this code through which it inserts node at the starting.This code also contains a function which prints linked list and if empty it prints linked list is empty .

when i run this code , i have my ouput as Linked list is empty .

struct node {
int data;
node* next;
}* start = NULL;

void append(node* linkedlist, int data)
{
node* new_element = NULL;
new_element = (node*)malloc(sizeof(struct node));
new_element->data = data;
if (linkedlist == NULL) {
linkedlist = new_element;
new_element->next = NULL;
}

else {
new_element->next = (linkedlist)->next;
(linkedlist)->next = new_element;
}
}

int main()
{
append(start, 4);
append(start, 5);
printList(start);
}


Update:

void printList(node* linkedlist)
{
node* ptr = linkedlist;
if (linkedlist == NULL) {
printf("Linked list is empty");
exit(0);
}
else {

while (ptr != NULL) {
cout << ptr->data;
ptr = ptr->next;
}
}
}


What could i be possibly doing wrong? What should i change in order to make it work?

Answer

Your problem is here linkedlist = new_element; When passing arguments to a function they are passed by value. Even when you pass a pointer you are actually passing a copy of that pointer(you can verify by printing the address of linkedlist inside the function and outside the function). The statement linkedlist = new_element; assigns the new_element to a copy. Once the function return you end up with nothing (and a memory leak). Remember when you need to change a pointer itself you must use a double pointer **

Comments