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…

#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;

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

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…

>Solution :

write this instead of what you did:

second->data = 20; //same
second->next = third;

third->data = 30; //same
third->next = NULL;

Leave a Reply