对于一个不带头结点的单链表L,设计一个递归算法逆置所有结点。编写完整的程序并进行测试,分析其时间复杂度。使用c99编写该脚本
时间: 2023-04-06 16:01:17 浏览: 58
我可以回答这个问题。以下是逆置单链表的递归算法的C99代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void reverseList(struct Node* curr, struct Node* prev, struct Node** head) {
if (curr->next == NULL) {
*head = curr;
curr->next = prev;
return;
}
struct Node* next = curr->next;
curr->next = prev;
reverseList(next, curr, head);
}
void insert(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
void printList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
insert(&head, 5);
insert(&head, 4);
insert(&head, 3);
insert(&head, 2);
insert(&head, 1);
printf("Original list: ");
printList(head);
reverseList(head, NULL, &head);
printf("Reversed list: ");
printList(head);
return 0;
}
```
该算法的时间复杂度为O(n),其中n是链表中的节点数。