#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data;
struct Node *next;
};
// 函数声明
struct Node* reverseList(struct Node* head);
// 主函数
int main() {
// 构建一个简单链表 1 -> 2 -> 3
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
struct Node* node2 = (struct Node*)malloc(sizeof(struct Node));
node2->data = 2;
struct Node* node3 = (struct Node*)malloc(sizeof(struct Node));
node3->data = 3;
head->next = node2;
node2->next = node3;
node3->next = NULL;
// 逆序链表
head = reverseList(head);
// 打印逆序后的链表
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
struct Node* temp = current;
current = current->next;
free(temp);
}
printf("NULL\n");
return 0;
}
// 逆序链表函数
struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL;
struct Node* current = head;
struct Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
return prev;
}
- 链表结构体定义:
- 定义了一个链表结构体
struct Node
,包含一个整数data
用于存储数据,以及一个指向下一个节点的指针next
。
- 函数声明:
struct Node* reverseList(struct Node* head);
声明了逆序链表的函数。
- 主函数:
- 构建了一个简单的链表
1 -> 2 -> 3
。
- 调用
reverseList
函数逆序链表。
- 打印逆序后的链表,并在打印过程中释放每个节点的内存。
- 逆序链表函数
reverseList
:
- 使用三个指针
prev
、current
和next
。
prev
初始化为NULL
,current
初始化为链表头节点head
,next
用于临时保存current
的下一个节点。
- 通过循环,将
current
节点的next
指针指向前一个节点prev
,并不断更新prev
和current
指针,最终返回新的链表头节点prev
。