以下是一个访问链表中结构体的示例代码:
#include <stdio.h>
// 结构体定义
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建链表
Node* createLinkedList() {
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;
head = (Node*)malloc(sizeof(Node));
second = (Node*)malloc(sizeof(Node));
third = (Node*)malloc(sizeof(Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
return head;
}
// 遍历链表并输出每个节点的值
void traverseLinkedList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* linkedList = createLinkedList();
traverseLinkedList(linkedList);
return 0;
}
上述代码中,首先定义了一个结构体Node
,其中包含一个整型变量data
和一个指向下一个节点的指针next
。然后使用createLinkedList
函数创建了一个包含3个节点的链表,并返回链表的头节点。最后使用traverseLinkedList
函数遍历链表并输出每个节点的值。
注意:上述代码为C语言示例,如果是其他编程语言,语法可能会有所不同,但基本思路是一样的。