I am confused why my code wouldn't print the good result when trying to add a node at the end of a linked list. I want to understand the logic behind it, I will show you two different codes the first one only prints the first node even if the list 'contains' more than one node, the second one works exactly as intended but I don't understand WHY or how it works.
First code: (The confusing one)
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
typedef struct Node Node;
Node *head;
void insertNode(int value){
Node *t = head;
//t = head;
if (head == NULL){
Node *tmp = malloc(sizeof(Node));
tmp->data = value;
tmp->next = NULL;
head = tmp;
}
else{
while (t != NULL) {
t = t->next;
}
Node *tmp = malloc(sizeof(Node));
tmp->data = value;
tmp->next = NULL;
t = tmp;
}
}
void showNode(){
Node *tmp = head;
while (tmp != NULL) {
printf("-> %d",tmp->data);
tmp = tmp->next;
}
}
int main(){
int n,value;
head = NULL;
printf("Node number: ");scanf("%d",&n);
for (int i = 0; i < n; i++) {
scanf("%d",&value);
insertNode(value);
}
showNode();
printf("\n");
return 0;
}
The second code: (The correct one)
The only difference is in the insertNode function,
void insertNode(int value){
Node *t = head;
//t = head;
if (head == NULL){
Node *tmp = malloc(sizeof(Node));
tmp->data = value;
tmp->next = NULL;
head = tmp;
}
else{
while (t->next != NULL) {
t = t->next;
}
Node *tmp = malloc(sizeof(Node));
tmp->data = value;
tmp->next = NULL;
t->next = tmp;
}
}
So, my question is HOW both codes work and what's wrong with the first code ?
Thank you, :)