2014-10-07 38 views
0

我正在尝试创建一个append_node方法来将节点添加到我创建的链表中。 我的节点结构如下定义:在链表中使用结构

typedef struct Node{ 
    struct Node next = NULL; 
    int id; 
} Node; 

然而,与下面的方法编译时,我得到以下错误: “节点”没有名为“身份证” “节点”成员没有名为“成员next'

void append_node(Node *sent,int val){ 
    Node *other_node = (struct Node *)malloc(1*sizeof(struct Node)); 
    other_node->id = val; 
    Node n = *sent; 
    while (n.next != NULL){ 
     n = n.next; 
    } 
    n.next = other_node; 
} 

为什么会发生此错误?

编辑:

我也有以下错误

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token 

的节点定义

+1

一个'struct'无法持有相同类型的实例为本身。 – juanchopanza 2014-10-07 19:20:04

+1

你可能的意思是:'struct Node * next = NULL;'(即缺少'*')。 – isedev 2014-10-07 19:20:48

+0

临时'n'应该是一个指针 – sp2danny 2014-10-07 19:24:59

回答

1

代码中有很多错误。
这里是一个正确的版本

typedef struct NodeTag 
{ 
    struct NodeTag* next; 
    int id; 
} Node; 

void append_node(Node* sent,int val) 
{ 
    Node* other_node = (Node*)malloc(sizeof(Node)); 
    other_node->id = val; 
    other_node->next = 0; 
    Node* n = sent; 
    while (n->next != 0) 
    { 
     n = n->next; 
    } 
    n->next = other_node; 
} 
+0

我尝试过使用这种方法,但是当我调用'Node lr'时 'lr.number = 0;' 'add_node(&lr,2);'我得到一个seg故障任何想法有什么问题? – teaLeef 2014-10-07 20:31:56

+0

是的,你没有设置旁边0 – sp2danny 2014-10-07 22:57:37

2

你已经不能再节点定义相同的结构内的第一线。这将是无限递归。

您可以将指针指向相同类型。

typedef struct Node{ 
    struct Node *next; 
+0

我改变了这一点,但我仍然有相同的编译错误... – teaLeef 2014-10-07 19:22:05

+0

没有执行看到节点定义?还有一些其他的头文件也定义了Node? – sp2danny 2014-10-07 19:24:20

+0

我不确定你的意思(新的c)。我在主函数 – teaLeef 2014-10-07 19:25:23