在我正在编写的程序中,我需要一个链表,所以它是一个非常具体的实现。它需要:
- 将节点添加到末尾的能力
- 删除数据与指定值匹配的节点的能力
数据为 cstring,长度不超过 20 个字符。我对 C 不是很有经验,并且遇到以下签名错误void addToEnd(llist root, char entery[51])
。我尝试替换llist
为,node
但错误是“未知类型名称节点”。我怎样才能摆脱这个?
这是代码
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct node
{
char entery[51];
struct node* next;
} llist;
/*may be losing root address permanently*/
void addToEnd(llist root, char entery[51])
{
while(root->next != NULL)
root = root->next;
node last = malloc(sizeof(struct node));
root->next = last;
strcpy(last, entery);
}
int main()
{
struct node *root = malloc(sizeof(struct node));
root->next = NULL;
strcpy(root->entery, "Hello");
struct node *conductor = root;//points to a node while traversing the list
if(conductor != 0)
while(conductor->next != 0)
conductor = conductor->next;
/* Creates a node at the end of the list */
conductor->next = malloc(sizeof(struct node));
conductor = conductor->next;
if (conductor == NULL)
{
printf( "Out of memory" );
return EXIT_SUCCESS;
}
/* initialize the new memory */
conductor->next = NULL;
strcpy(conductor->entery, " world\n");
addToEnd(root, " at the");
addToEnd(root, " end");
/*print everything in list*/
conductor = root;
if(conductor != NULL)
{
while(conductor->next != NULL)
{
printf("%s", conductor->entery);
conductor = conductor->next;
}
printf("%s", conductor->entery);
}
return EXIT_SUCCESS;
}
我不清楚的一件事是,在我看到的所有示例中,它们都是typedef struct。为什么?让我详细说明一下:你怎么知道你是想通过node
还是struct node
. 此外,我真的不明白这一点,struct node
不比单个 typedef 名称长多少。