0

I have created a function which will return the base address of the linked list. It is always returning the last node address(null) instead of the first node.

#include<stdio.h>
#include<stdlib.h>
typedef struct _LinkedList
{
    int data;
    struct LinkedList *nextVal;
}LinkedList;


//function to create a linked list
LinkedList* createLL()
{
    LinkedList *ll;
    ll=malloc(sizeof(LinkedList));
    ll->nextVal =malloc(sizeof(LinkedList));
    int i;
    int count = 5;
    for(i=0;i<5;i++)
    {
        ll->nextVal = malloc(sizeof(LinkedList));
        ll->data = i;
        printf("LL data value %d address val %p\n ",ll->data,ll->nextVal);

    }
    //last node should point to null
    ll->nextVal=NULL;
    printf("======================\n");
    return ll;
}


int main()
{

    LinkedList *basePtr;
    int i;
    basePtr=createLL();
    for(i=0;i<5;i++)
    {
         printf("LL data value %d address val %p\n ",basePtr->data,basePtr->nextVal);   

    }
    return 0;
}

1 Answer 1

1

In both createLL() and main(), inside the two for loops, you don't update the head pointer of the list, you just overwrite the original pointer. (I. e., you don't have a linked list, you have five dangling nodes of which four leak memory). How about something like this:

LinkedList *createLL()
{
     LinkedList *head = NULL;

     for (int i = 0; i < 5; i++) {
         // use sizeof(*pointer) instead of sizeof(type), by the way
         LinkedList *tmp = malloc(sizeof(*tmp));
         tmp->next = head;
         tmp->data = i;
         head = tmp;
     }

     return head;
}

Repeat this patter in main(), and you're good to go.

Sign up to request clarification or add additional context in comments.

2 Comments

This will return the last node value right? Not the first one?
@user968000 it will build the list in reverse order, but you will have access to all of the nodes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.