gpt4 book ai didi

c - C语言链表中的节点

转载 作者:行者123 更新时间:2023-11-30 14:41:37 25 4
gpt4 key购买 nike

我开始学习链表,所以我的问题可能很愚蠢:p。我注意到在所有练习中,它们只在节点中获取一个数据元素(如下所示:int data)。所以我想问我们是否可以在一个节点中定义多个数据元素。否则为什么不呢?

#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node* nextptr;
};

struct node* BuildList()
{
/* initialize node's pointers */
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;
/* allocate three nodes in the heap*/
head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));
/* setup first node */
head->data = 1;
head->nextptr = second;

second->data = 2;
second->nextptr = third;
third->data =3;
third->nextptr = NULL;

return head;
}

最佳答案

是的,int 只是让示例变得更容易。但在现实生活中,节点将是更有用的东西。示例:

struct chair {
int nr_or_legs;
int weight_in_kg;
int height_in_cm;
};

struct chair_node {
struct chair data;
struct chair_node* nextptr;
};

或者只是:

struct chair_node {
int nr_or_legs;
int weight_in_kg;
int height_in_cm;
struct chair_node* nextptr;
};

关于c - C语言链表中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54851665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com