Creating a linked list and traversal

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?

Head is updated through temp. In C/C++, pointers are used heavily and two pointers can point to the same memory and change its contents.

Consider

#include<studio.h>

int main() {
  // a is an int, b is an int pointer
  int a = 7;
  int *b;

  // Set b to point to a
  b = &a;

  // Print
  printf("Before:/n", stdout);
  printf("a: %d/n", a, stdout);
  printf("b: %d/n", *b, stdout);

  // Change memory b points to
  *b = 13;

  // Print
  printf("/nAfter/n", stdout);
  printf("a: %d/n", a, stdout);
  printf("b: %d/n", *b, stdout);


  return 0;
}

Your example makes perfect sense; I know how pointers (well somewhat) work but in case of linked lists I couldn’t visualized it. Now it’s clear. Thanks a lot!

I followed you on GitHub btw, seeing that you code in C mostly. I’ve always gotten back to C from time to time and it seems I’m learning something new about it everyday.

1 Like

I’m glad I was able to help!