我试图在C中创建一个链表结构。不过,我不太确定出了什么问题。我的错误是:

linked.c:6:2: error: unknown type name ‘linkedList’
linked.c: In function ‘makeList’:
linked.c:30:2: error: ‘first’ undeclared (first use in this function)
linked.c:30:2: note: each undeclared identifier is reported only once for each function it appears in
linked.c: In function ‘addToList’:
linked.c:36:9: error: used struct type value where scalar is required
linked.c:43:13: error: incompatible types when assigning to type ‘int *’ from type ‘linkedList’

如果有人能看出问题所在并向我解释,我将不胜感激。我的代码在下面。
#include <stdio.h>

typedef struct linkedList
{
        int first;
        linkedList* rest;
} linkedList;

linkedList makeList(int a, int b, int c);
void addToList(linkedList* ll, int a);

int main()
{
        linkedList ll = makeList(1,3,5);
        addToList(&ll, 7);
        addToList(&ll, 9);
        return 0;
}

linkedList makeList(int a, int b, int c)
{
        linkedList ll;
        ll.first = a;
        linkedList second;
        second.first = b;
        linkedList third;
        third.first = c;
        third.rest = NULL;
        second.rest = &c;
        first.rest = &b;
        return first;
}

void addToList(linkedList* ll, int a)
{
        while (*ll)
        {
                if (ll->rest == NULL)
                {
                    linkedList newL;
                    newL.first = a;
                    newL.rest = NULL;
                    ll->rest = newL;
                    break;
            } else
            {
                    continue;
            }
    }
}

最佳答案

以下是程序的更正版本:

#include <stdio.h>
#include <stdlib.h>


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

关于c - 试图在C中创建链表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19144891/

10-11 22:59
查看更多