单链表逆置c语言代码
时间: 2023-10-20 15:08:59 浏览: 57
单链表逆置的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* nextTmp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTmp;
}
return prev;
}
// 测试函数
void test() {
// 创建链表节点
struct ListNode* node1 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* node2 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* node3 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* node4 = (struct ListNode*)malloc(sizeof(struct ListNode));
// 初始化链表节点的值
node1->val = 1;
node2->val = 2;
node3->val = 3;
node4->val = 4;
// 构建链表关系
node1->next = node2;
node2->next = node3;
node3->next = node4;
node4->next = NULL;
// 输出原始链表
printf("原始链表:");
struct ListNode* curr = node1;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
// 单链表逆置
struct ListNode* newHead = reverseList(node1);
// 输出逆置后的链表
printf("\n逆置后的链表:");
curr = newHead;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
// 释放内存
free(node1);
free(node2);
free(node3);
free(node4);
}
int main() {
test();
return 0;
}
```