【发布时间】:2013-10-05 03:46:57
【问题描述】:
在我正在编写的程序中,我需要一个链表,所以它是一个非常具体的实现。它需要:
- 能够将节点添加到末尾
- 能够删除数据与指定值匹配的节点
数据是一个cstring,长度不超过20个字符。我对 C 语言不是很熟悉,并且遇到以下签名 void addToEnd(llist root, char entery[51]) 的错误。我尝试用node 替换llist,但错误是“未知类型名称节点”。我怎样才能摆脱它?
这是代码
#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 the struct。为什么?让我详细说明一下:你怎么知道你是想通过node 还是struct node。另外,我真的不明白这一点,struct node 并不比单个 typedef 名称长多少。
【问题讨论】:
-
使用您的 typedef,
llist与struct node相同... -
为什么过去的结构节点,节点是类型,为什么需要结构?
-
@Celeritas 在
C中,struct node是一种类型,但不是node。在C++等其他语言中,somename等价于struct somename。
标签: c linked-list malloc