经过研究原来是可以定义一个结构体的,结构体里面本身还可以包含自身类型的指针,真是好神奇。
- #include <stdio.h>
- #include <stdlib.h>
- // 定义链表节点
- struct Node {
- int data;
- struct Node *next;
- };
- // 插入节点到链表头部
- void insertAtBeginning(struct Node **head, int data) {
- // 创建新节点
- struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
- newNode->data = data;
- // 将新节点插入到链表头部
- newNode->next = *head;
- *head = newNode;
- }
- // 打印链表
- void printList(struct Node *head) {
- struct Node *temp = head;
- while (temp != NULL) {
- printf("%d -> ", temp->data);
- temp = temp->next;
- }
- printf("NULL\n");
- }
- int main() {
- // 初始化链表头指针
- struct Node *head = NULL;
- // 插入一些元素到链表中
- insertAtBeginning(&head, 5);
- insertAtBeginning(&head, 10);
- insertAtBeginning(&head, 15);
- // 打印链表
- printf("链表内容:\n");
- printList(head);
- return 0;
- }
|