Trying to make linkedlist in C

后端 未结 4 964
余生分开走
余生分开走 2021-01-27 19:43

I am trying to make a struct in C that is a linked list. I am not really sure what is going wrong though. My errors are:

linked.c:6:2: error: unknown type name         


        
4条回答
  •  我在风中等你
    2021-01-27 20:37

    A few observations,

    • declare a struct name so that you can use it in the linkedList struct.
    • DRY - Don't Repeat Yourself, that is why the below ListNew() function is provided
    • use pointers, that is the whole point to building a linked list anyway,
    • your list uses one type of node, storing data and the list pointer,
    • name the pointer to the next node in the list whatever you want, how about 'next'?
    • name the thing that holds data anything you want, how about 'data'?
    • print the list, it will help figure out what is going on, :-)
    • a pointer can be printed in hexadecimal using the %x print format

    Anyway, here is a single linked list, without keeping track of the tail of the list, or counting the elements.

    #include 
    #include 
    
    typedef struct listnode
    {
        int data;
        struct listnode* next;
    } linkedList;
    linkedList* makeList(int a, int b, int c);
    void addToList(linkedList* ll, int a);
    void ListPrint(linkedList* ll);
    int main()
    {
        linkedList* ll = makeList(1,3,5);
        addToList(ll, 7);
        addToList(ll, 9);
        ListPrint(ll);
        return 0;
    }
    linkedList* ListNew(int a) //new linkedList node
    {
        linkedList* newL = (linkedList*)malloc(sizeof(linkedList));
        newL->data = a;
        newL->next = NULL;
        return newL;
    }
    linkedList* makeList(int a, int b, int c)
    {
        linkedList* ll = ListNew(a);
        addToList(ll, b);
        addToList(ll, c);
        return ll;
    }
    void addToList(linkedList* ll, int a)
    {
        if(!ll) return;
        //find end of list
        while (ll->next)
        {
            ll = ll->next;
        }
        ll->next = ListNew(a);
        return;
    }
    void ListPrint(linkedList* ll) //print list
    {
        if(!ll) return;
        linkedList* p;
        for( p=ll; p; p=p->next )
        {
            printf("%x: %d\n",p,p->data);
        }
        return;
    }
    

提交回复
热议问题