[英]Using structures in a linked list
我正在嘗試創建一個append_node方法,以將節點添加到我創建的鏈表中。 我的節點結構定義如下:
typedef struct Node{
struct Node next = NULL;
int id;
} Node;
但是,使用下面的方法進行編譯時,出現以下錯誤:'Node'沒有名為'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
在節點定義的第一行
您不能在同一結構內再次定義Node。 這將是無限遞歸。
您可以擁有一個指向相同類型的指針。
typedef struct Node{
struct Node *next;
您的代碼中有很多錯誤。
這是正確的版本
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.