要求单独写一个函数来实现单链表的逆置,并编写代码在main函数测试结果。首先输入一个整数N,表示测试数据的组数,然后是N组测试数据。每组测试数据在一行上先输入数据个数n及n个整数。对于每组测试,输出逆置后的单链表,每两个数据之间留一个空格,行末不能有多余的空格
时间: 2023-06-08 09:04:09 浏览: 69
单链表逆置的完整实现java版
非常感谢您的提问。以下是关于单链表的逆置的代码:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
struct ListNode {
int val;
struct ListNode *next;
};
// 单链表的逆置函数
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode *prev = NULL;
struct ListNode *curr = head;
while (curr != NULL) {
struct ListNode *nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
// 测试函数
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
int num;
scanf("%d", &num);
// 构建单链表
struct ListNode *head = NULL;
struct ListNode *curr = NULL;
for (int j = 0; j < num; ++j) {
int val;
scanf("%d", &val);
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
if (head == NULL) {
head = node;
} else {
curr->next = node;
}
curr = node;
}
// 逆置单链表
struct ListNode *reversedHead = reverseList(head);
// 输出逆置后的结果
while (reversedHead != NULL) {
printf("%d ", reversedHead->val);
reversedHead = reversedHead->next;
}
printf("\n");
}
return 0;
}
阅读全文