链表——指针的终极大招
这个是指针的杀手锏应用,数据结构界的明星:
- #include <stdio.h>
- #include <stdlib.h>
- struct Node {
- int data;
- struct Node *next;// 指向下一个节点的指针
- };
- void printList(struct Node *head) {
- struct Node *current = head;
- printf("链表内容:");
- while(current != NULL) {
- printf("%d -> ", current->data);
- current = current->next;
- }
- printf("NULL\n");
- }
- int main() {
- // 创建三个节点
- struct Node *first = (struct Node*)malloc(sizeof(struct Node));
- struct Node *second = (struct Node*)malloc(sizeof(struct Node));
- struct Node *third = (struct Node*)malloc(sizeof(struct Node));
- // 填充数据并连接
- first->data = 10;
- first->next = second;
- second->data = 20;
- second->next = third;
- third->data = 30;
- third->next = NULL;
- printList(first); // 输出:10 -> 20 -> 30 -> NULL
- // 释放内存
- free(first);
- free(second);
- free(third);
- return0;
- }
链表就像火车,每节车厢都知道下一节在哪里!
|