请用C语言设计一个非常简单的算法,实现单链表反转
时间: 2024-03-07 21:47:00 浏览: 76
用C语言实现单链表的各种操作(一)
以下是一个更简单的C语言实现单链表反转的算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
ListNode* reverseList(ListNode* head) {
ListNode *prev = NULL, *curr = head;
while (curr != NULL) {
ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
ListNode *head = (ListNode*)malloc(sizeof(ListNode));
head->val = 1;
head->next = (ListNode*)malloc(sizeof(ListNode));
head->next->val = 2;
head->next->next = (ListNode*)malloc(sizeof(ListNode));
head->next->next->val = 3;
head->next->next->next = NULL;
printf("Original list: ");
ListNode *curr = head;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
printf("\n");
head = reverseList(head);
printf("Reversed list: ");
curr = head;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
printf("\n");
return 0;
}
```
该算法与之前的算法类似,但是省去了一个指针变量,直接在while循环内部定义了一个指向下一个节点的指针变量next。这样可以使代码更加简洁。
阅读全文