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;
}
4

1 回答 1

1

createLL()andmain()中,在两个for循环中,您不会更新列表的头指针,而只是覆盖原始指针。(即,您没有链表,您有五个悬空节点,其中四个泄漏内存)。像这样的东西怎么样:

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

重复这个模式main(),你就可以开始了。

于 2013-09-15T04:58:36.700 回答