Hi everyone. I’m new here and I’ve come with a problem that I’m having trouble to understand.
I have the following code that I wrote following a tutorial that creates and traverses a linked list.
#include<stdio.h>
#include<stdlib.h>
typedef struct node Node;
struct node
{
int data;
Node *next;
};
Node *head;
// functions to create list
void create_list(int n)
{
Node *new_node, *temp;
int data, i;
head = (Node *)malloc(sizeof(Node));
if (head == NULL) {
printf("Sorry! Could not allocate memory.\n");
exit(1);
}
printf("Enter data of node 1: ");
scanf("%d", &data);
head->data = data;
head->next = NULL;
temp = head;
for (i = 2; i <= n; i++) {
new_node = (Node *)malloc(sizeof(Node));
if (new_node == NULL) {
printf("Sorry! Could not allocate memory.\n");
exit(1);
}
printf("Enter data of node %d: ", i);
scanf("%d", &data);
new_node->data = data;
new_node->next = NULL;
temp->next = new_node;
temp = temp->next;
}
}
void traverse_list()
{
Node *temp;
//if list is empty
if (head == NULL) {
printf("List is empty.\n");
exit(1);
}
temp = head;
while (temp != NULL) {
printf("Data = %d\n", temp->data);
temp = temp->next;
}
}
int main()
{
int n;
printf("Enter the number of nodes for a linked list: ");
scanf("%d", &n);
create_list(n);
printf("\nData in created linked list:\n");
traverse_list();
return 0;
}
Now the head->next
is set to NULL
and that doesn’t change. So how is the traversal working after the first item is printed?