尝试在 C 中制作链表 [英] Trying to make linkedlist in C
本文介绍了尝试在 C 中制作链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在 C 中创建一个链表结构.我不太确定出了什么问题.我的错误是:
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 ‘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’
如果有人能看到问题所在并向我解释,我将不胜感激.我的代码如下.
if anybody can see what is wrong and explain it to me, it would be much appreciated. My code is below.
#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;
}
}
}
推荐答案
这是您程序的更正版本:
here's a corrected version of your program :
#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
" , ll->first);
go_trough(ll->rest);
}
}
这篇关于尝试在 C 中制作链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文