创建循环链表

时间:2013-09-21 02:40:38

标签: c linked-list

我很长时间没有使用链表,我无法弄清楚为什么这段代码失败了。我正在尝试创建一个非常简单的循环链表,其中包含5个节点。我永远不需要插入额外的节点也不需要删除现有节点。

我收到'node' has no member named 'next'错误。谁能告诉我我做错了什么?感谢。

typedef struct {
    char payload[1024];
    int x;
    node* next;
} node;

node* root_ptr;
node this_node; 

root_ptr = malloc(sizeof(node *));
root_ptr = &this_node; //keep a pointer to the root
int i;
for (i=0; i<5; i++) {
    node next_node;
    this_node.next = &next_node;
    this_node = next_node;
}
this_node.next = root_ptr;

3 个答案:

答案 0 :(得分:3)

在您的struct成员中,typedef名称仍然未知。因此,应该为您的结构命名,然后您可以用它声明一个标识符:

它会起作用:

typedef struct node_t {
    char payload[1024];
    int x;
    struct node_t* next;
} node;

答案 1 :(得分:2)

首先,root_ptr = malloc(sizeof(node *));是多余的。

第二个node next_node;定义一个局部变量,它将在for循环后超出范围。您需要为next_node动态分配内存。

第三,你有6个节点,包括根,而不是5。

答案 2 :(得分:0)

试试这个:

int main(){

    // create root and helper nodes
    node * root_ptr;
    node * this_node = (node *)malloc(sizeof(node)); 

    this_node->x = 0;

    root_ptr = this_node; //keep a pointer to the root
    int i;
    // create list
    for (i=1; i<5; i++) {
        node * next_node = malloc(sizeof(node));
        next_node->x = i;
        this_node->next = next_node;
        this_node = next_node;
    }
    // complete cycle
    this_node->next = root_ptr;

    this_node = root_ptr;
    // check
    for (i=0; i<5; i++){
        printf("%d\n", this_node->x);
        this_node=this_node->next;
    }
    return 0;
}

请注意,在链接列表中分配堆栈内存通常是个坏主意

相关问题