0

リンク リストのベース アドレスを返す関数を作成しました。最初のノードではなく、常に最後のノード アドレス (null) を返します。

#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

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

でこのパタパタを繰り返すmain()と、準備完了です。

于 2013-09-15T04:58:36.700 に答える