Hi I'm a newbie learning Linked List, I created this sample program ,but it is not populating all the list, only last two are getting populated (or these overwriting the first linked elements)
Can someone please help me what is causing the issue ?
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *link;
};
void appendNode(int data, struct node **ptr) {
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->link = NULL;
if(*ptr == NULL) {
*ptr = newnode;
} else {
while((*ptr)->link != NULL ) {
*ptr = (*ptr)->link;
}
(*ptr)->link = newnode;
}
}
void printList(struct node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->link;
}
}
int main() {
struct node *head = NULL ;
appendNode(23,&head);
appendNode(45,&head);
appendNode(32,&head);
appendNode(11,&head);
appendNode(98,&head);
printList(head);
}
Ir prints
11 98
What is causing the issue here ?