C语言的链表中的节点

时间:2019-02-24 12:00:36

标签: c linked-list

我开始学习链表,所以我的问题可能是愚蠢的: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;
}

1 个答案:

答案 0 :(得分:1)

是的,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;
};