Trying to make linkedlist in C

后端 未结 4 904
余生分开走
余生分开走 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:21

    here's a corrected version of your program :

    #include 
    #include 
    
    
    typedef struct linkedList
    {
            int first;
            struct linkedList* rest; // add struct in the beginning 
    } linkedList;
    
    linkedList* addToList(linkedList* ll, int a);
    void go_trough(linkedList *ll); // here's an extra function to check 
    
    int main()
    {
            linkedList *ll ; // working with a pointer is easier and makelist is pointless work with add to list instead
            ll = NULL; // initialize to NULL
            ll = addToList(ll, 7);
            ll = addToList(ll, 9);
        go_trough(ll);
            return 0;
    }
    
    linkedList* addToList(linkedList* ll, int a) // I didn't understand what you were trying to do so ... here's my version
    {
         if(!ll)
         {
             ll = malloc(sizeof(linkedList*)); //allocating enought space to hold the structure
             ll->first = a;
             ll->rest = NULL;
         }
         else
             ll->rest = addToList(ll->rest , a);
         return ll;
    }
    void go_trough(linkedList *ll) 
    {
         if(ll)
         {
             printf("%d\n" , ll->first);
             go_trough(ll->rest);
         }   
    }
    

提交回复
热议问题