这段代码来自我正在学校为数据结构模块工作的作业。这个代码是在问题中提供的,我无法理解这一点。
typedef struct _listnode {
int item;
struct _listnode *next;
} ListNode; // You should not change the definition of ListNode
typedef struct _linkedlist {
int size;
ListNode *head;
} LinkedList; // You should not change the definition of LinkedList
我感到很困惑,因为我的演讲幻灯片和我去过的网站已经确定了节点,而不是第二个节点。
有人可以帮我这个吗?
答案 0 :(得分:1)
LinkedList
是一个结构,通过保持其头部及其大小来表示链表,而列表中的每个节点都由结构ListNode
表示。如果您想要保持链表的大小,这是一个常见的范例,如果您可以轻松获取列表中的节点数而无需迭代它。另一方面,如果不考虑大小,您可以只使用指向节点的指针而不必定义LinkedList
结构。
因此,对于一个空列表,您将拥有:
LinkedList list = (struct LinkedList){0, NULL};
对于包含一个节点的列表:
ListNode node;
node.item = 0;
node.next = NULL;
list.head = &node;
list.size = 1;
答案 1 :(得分:0)
链接列表使用指向列表第一项的本地指针变量来保存。如果该指针也为NULL,则该列表被视为空。
include <stdio.h>
int main() {
typedef struct node {
int val;
struct node * next;
} node_t;
return 0;
}