C语言中链表的两种结构
好的,我正在为单链表创建一个ADT。我有一个结构名列表,它存储指向第一个节点(列表中的第一项,也是一个结构)的指针和大小。该节点存储第一个名称和指向下一个节点的指针。以下是这些照片:C语言中链表的两种结构,c,struct,malloc,singly-linked-list,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为结构列表提供内存: ListP
typedef struct List *ListP;
struct List{
ListP head;
int size;
};
struct node{
char name[20];
nodeP next;
};
首先,我调用malloc为结构列表提供内存:
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->head分配到新节点的地址
newList->head=newNode
直到这时,编译器才开始抱怨。但当我尝试使用列表指针访问第一个节点中的元素时:
name = newList->head->name;
编译器抱怨结构列表没有名为“name”的成员
假设我只有指向struct List的指针,并且List->head指向第一个节点,那么如何访问struct节点中的字段。
如果有任何帮助,我们将不胜感激。假设NodeP是一个节点*,您将head声明为
ListP
类型
试着与名字保持一致。以下是建议的修订:
// 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;
};
typedef结构节点*nodeP代码><代码>列表头代码>-->节点头代码>。