用c代码写程序,实现单链表反转并注释解析
时间: 2023-05-22 19:01:12 浏览: 73
当然可以,以下是一个简单的单链表反转的 C 代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode *prev = NULL;
struct ListNode *curr = head;
while (curr != NULL) {
struct ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
// 创建链表
struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode));
head->val = 1;
head->next = (struct ListNode *)malloc(sizeof(struct ListNode));
head->next->val = 2;
head->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
head->next->next->val = 3;
head->next->next->next = NULL;
// 反转链表
struct ListNode *newHead = reverseList(head);
// 输出链表
while (newHead != NULL) {
printf("%d ", newHead->val);
newHead = newHead->next;
}
printf("\n");
return 0;
}
```
注释解析:
1. 定义链表结构体 `ListNode`,包含一个整数 `val` 和一个指向下一个节点的指针 `next`。
2. 定义 `reverseList` 函数,接收一个链表头节点 `head`,返回反转后的链表头节点。使用三个指针 `prev`、`curr`、`next` 分别表示当前节点的前一个节点、当前节点、当前节点的后一个节点,遍历链表,每次将当前节点的 `next` 指向前一个节点,然后将三个指针向后移动一位,直到遍历完整个链表。
3. 在 `main` 函数中创建一个包含三个节点的链表,然后调用 `reverseList` 函数反转链表,最后输出反转后的链表。
4. 代码中的注释解释了每个变量和函数的作用,方便理解和阅读。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)