用C语言写一个函数。将3个节点的链表反转过来。并写出测试case
时间: 2023-04-03 11:01:55 浏览: 108
以下是用 C 语言编写的反转链表函数及测试用例:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node* next;
} Node;
Node* reverseList(Node* head) {
Node* prev = NULL;
Node* curr = head;
Node* next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
Node* head = (Node*)malloc(sizeof(Node));
head->val = 1;
head->next = (Node*)malloc(sizeof(Node));
head->next->val = 2;
head->next->next = (Node*)malloc(sizeof(Node));
head->next->next->val = 3;
head->next->next->next = NULL;
printf("Original list: ");
printList(head);
head = reverseList(head);
printf("Reversed list: ");
printList(head);
return ;
}
```
测试结果:
```
Original list: 1 2 3
Reversed list: 3 2 1
```
阅读全文