【发布时间】:2021-08-29 13:01:08
【问题描述】:
我正在尝试编写一个函数ReverseRange(struct Node **head, int x, int y),它将反转给定索引范围内的链表int x 和int y。我在ReverseRange() 的条件之一中使用了先前定义的函数Reverse(),但它没有反转给定的列表,只打印一个带有数据'Q' 的节点。我不知道错误是否在Print() 或Reverse() 或ReverseRange() 或其他地方。请帮忙,谢谢。
#include <stdio.h>
#include <stdlib.h>
struct Node {
char data;
struct Node *next;
};
//insert data in the node
void Insert(struct Node **Head, char data) {
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = data;
temp->next = *Head;
*Head = temp;
}
//find length of linked list
int LengthRec(struct Node *head) {
if (head == NULL)
return 0;
return 1 + LengthRec(head->next);
}
//Reverse a linked list when head is given;
void Reverse(struct Node **head) {
struct Node *prev = NULL;
struct Node *curr = *head;
struct Node *next = NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
*head = prev;
}
//Reverse list in range x to y;
int ReverseRange(struct Node **H, int x, int y) {
struct Node *Head = *H;
if (Head == NULL)
return -1;
else if (Head->next == NULL)
return -1;
else if (x == y)
return -1;
else if (x > y)
return -1;
else if (LengthRec(Head) >= y) {
if (x == 1 && y == LengthRec(Head)) {
Reverse(&Head);
return 1;
}
/* NOTE::
Code is incomplete, because I found error before
the entire code is written,
*/
}
}
void Print(struct Node **H) {
struct Node *head = *H;
if (head == NULL) {
printf("Head=NULL");
return;
}
printf("\n %c", head->data);
while (head->next != NULL) {
head = head->next;
printf("\t%c", head->data);
}
}
int main() {
struct Node *Head = NULL;
Insert(&Head, 'Q');
Insert(&Head, 'W');
Insert(&Head, 'E');
Insert(&Head, 'R');
Insert(&Head, 'T');
Print(&Head);
Reverse(&Head);
Print(&Head);
ReverseRange(&Head, 1, 5);
Print(&Head);
}
输出:
T R E W Q
Q W E R T
Q
【问题讨论】:
标签: c linked-list