2014-10-07 39 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