c语言单向链表的原地反转
时间: 2025-02-14 21:52:55 浏览: 45
### C语言中单向链表原地反转的实现
在C语言中,可以通过迭代的方式实现单向链表的原地反转。这种方法不需要额外的空间来存储新的节点,只需要几个指针变量来进行操作。
定义一个结构体用于表示链表节点:
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
```
下面是具体的反转函数实现[^2]:
```c
void reverseLinkedList(Node** headRef) {
Node* prev = NULL;
Node* current = *headRef;
Node* next;
while (current != NULL) {
next = current->next; // Store the next node
current->next = prev; // Reverse the link
prev = current; // Move prev to this node
current = next; // Move to the next node
}
*headRef = prev; // Update the head pointer
}
```
这段代码通过三个指针`prev`, `current`, 和`next`完成链表反转的操作。初始状态下,`prev`指向NULL,而`current`指向头节点。随着循环推进,逐步更新这三个指针的位置直到遍历整个列表并最终改变其方向。
为了验证这个算法的有效性,下面是一个简单的测试程序片段:
```c
int main() {
// 创建链表 1 -> 2 -> 5 -> 3 -> 4
Node* head = malloc(sizeof(Node));
head->data = 1;
Node* second = malloc(sizeof(Node));
second->data = 2;
Node* third = malloc(sizeof(Node));
third->data = 5;
Node* fourth = malloc(sizeof(Node));
fourth->data = 3;
Node* fifth = malloc(sizeof(Node));
fifth->data = 4;
head->next = second;
second->next = third;
third->next = fourth;
fourth->next = fifth;
fifth->next = NULL;
printf("Original list:\n");
printList(head);
reverseLinkedList(&head);
printf("\nReversed list:\n");
printList(head);
}
// 打印链表辅助函数
void printList(Node* n) {
while(n != NULL){
printf("%d ", n->data);
n = n->next;
}
}
```
此段代码创建了一个包含五个整数(1, 2, 5, 3, 4)的单向链表,并调用了上述提到的反转函数对其进行处理。之后打印原始和翻转后的链表以便观察效果。
阅读全文
相关推荐



















