请用C语言设计一个简单的算法,实现单链表反转(一定要简单!!!)
时间: 2024-01-27 10:03:38 浏览: 70
以下是一个简单的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, *next = NULL;
while (curr != NULL) {
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;
}
```
该算法使用三个指针prev、curr和next,分别指向反转后的链表头部、当前节点和下一个节点。在遍历链表的过程中,将当前节点的next指针指向prev,然后将prev指针移动到当前节点,将curr指针移动到下一个节点。最后返回prev指针,即为反转后的链表头部。
阅读全文