How do I print all the nodes in a linked list?

I am trying to teach myself linked lists, so I have managed to put together a small piece of code that should create three linked nodes and then print them out. Except it only prints out the first element, and I don't understand why not the other two.

Also, I am pretty sure I am supposed to free memory when I use malloc? but I don't know where?

Anyway, what am I doing wrong?? here is the code...

I know that there are similar answers out there, but I have checked them out, and would prefer an answer to my specific situation, because I wouldn't get it otherwise...

#include<stdio.h>
#include <stdlib.h>

struct Node 
{
    int data;
    struct Node *next;
};

void printList(struct Node *ptr);

int main(void)
{
    struct Node* head = NULL;
    struct Node* second = NULL;
    struct Node* third = NULL;

    head = (struct Node*)malloc(sizeof(struct Node));
    second = (struct Node*)malloc(sizeof(struct Node));
    third = (struct Node*)malloc(sizeof(struct Node));

    head->data = 10;
    head->next = second;

    second->data = 20;
    head->next = third;

    third->data = 30;
    head->next = NULL;
    
    printList(head);
}

void printList(struct Node *ptr)
{
    struct Node *listPtr;
    listPtr = ptr;
    int count = 1;
    if (listPtr == NULL)
    {
        printf("No elements in list.\n");
        return;
    }  
    while (listPtr!=NULL)
    {
        printf("element %d = %d\n",count,listPtr->data);
        listPtr = listPtr->next;
        count++;
    }
}

I have looked into similar code examples, and they (at least a couple of them), look similar to mine, so I don't really know what I am doing wrong...



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation