c 语言 单链表 反转
时间: 2023-09-26 11:07:32 浏览: 40
好的,下面是 C 语言单链表反转的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int data;
struct Node* next;
};
// 定义函数实现单链表反转
struct Node* reverseList(struct Node* head) {
struct Node* prev = NULL;
struct Node* curr = head;
struct Node* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// 定义函数实现创建链表
struct Node* createList(int arr[], int size) {
struct Node* head = NULL;
struct Node* tail = NULL;
for (int i = 0; i < size; i++) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = arr[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 定义函数实现打印链表
void printList(struct Node* head) {
struct Node* curr = head;
while (curr != NULL) {
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
struct Node* head = createList(arr, size);
printList(head);
struct Node* newHead = reverseList(head);
printList(newHead);
return 0;
}
```
代码实现的主要思路是,设置三个指针,分别指向当前节点、前一个节点和下一个节点,然后通过遍历链表,依次将当前节点指向前一个节点,再将当前节点、前一个节点和下一个节点向后移动,直到当前节点为 NULL 时结束循环,最后返回新的头节点。