I am a newbie in the data structure. I am creating a linked list program. I have created the program. But don't understand why insertAtTail is not adding the node to linked list.
struct node {
int data;
struct node *next;
};
struct node *head=NULL;
int main( void ) {
insertAtHead(3);
insertAtHead(4);
insertAtHead(5);
insertAtHead(8);
insertAtTail(2);
display();
return 0;
}
void insertAtHead( int data ){
struct node *newNode;
newNode = (struct node *)malloc( sizeof(struct node) );
newNode->data = data;
newNode->next = NULL;
if( head == NULL ){
head = newNode;
} else {
newNode->next = head;
head = newNode;
}
}
void insertAtTail(int data){
struct node *newNode, *temp;
newNode = (struct node *)malloc( sizeof(struct node) );
newNode->data = data;
newNode->next = NULL;
if( head == NULL){
head = newNode;
} else {
temp = head;
while ( temp != NULL){
temp = temp->next;
}
temp = newNode;
}
}
void display(){
struct node *temp;
temp = head;
while ( temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
Expect the output: 8 -> 5 -> 4 -> 3 -> 2 -> NULL
Actual Output: 8 -> 5 -> 4 -> 3 -> NULL