C中链表的两个结构

时间:2014-10-04 21:42:28

标签: c struct malloc singly-linked-list

好的我正在创建单链表的ADT。我有一个结构名称列表,存储指向第一个节点(列表中的第一个项目,也是一个结构)和大小的指针。节点存储名字和指向下一个节点的指针。这是鲟鱼:

typedef struct List *ListP;

struct List{
   ListP head;
   int size;
   };

struct node{
   char name[20];
   nodeP next;
   };

首先,我调用malloc为struct List提供内存:

ListP newList;
    newList = malloc(sizeof(struct List)); //should I typecast this to (ListP *)?
    if (newList == NULL){
         fprintf(stderr, "Memory allocation failed");
    }
    else{
        newList->head = NULL;    
        newList->size = 0;       
    }

然后我再次给malloc打电话给我第一个节点的记忆:

struct node *new;
    newNode = malloc(sizeof(struct node));
    if (newNode == NULL){
         fprintf(stderr, "Memory allocation failed");
    }
    else{
        newNode->name = 'Jay';
        newNode->next = NULL;  

现在我有了List和一个新节点,我将list->指定给了新节点的地址;

newList-> head = newNode;

直到这次编译器没有抱怨。但是当我尝试使用我对列表的指针访问第一个节点中的元素时:

name = newList->head->name;

编译器抱怨struct List没有名为' name'

的成员

我如何访问struct节点中的字段,假设我只有指向struct List和List->指向第一个节点的指针。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

如果假设NodeP是节点*,那么当它应该是ListP类型时,你声明为NodeP

尝试与名字保持一致。以下是建议的修订版:

// forward declarations
struct List;
struct Node;

typedef struct List *ListP;
typedef struct Node *NodeP;

struct Node{
   char name[20];
   NodeP next;
};

struct List{
   NodeP head;
   int size;
};