Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

write this instead of what you did:

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

third->data = 30; //same
third->next = NULL;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading