【发布时间】:2020-11-23 14:12:45
【问题描述】:
给定一个双向链表,将链表逆时针旋转 P 个节点。这里 P 是给定的正整数,并且小于链表中的节点数 (N)。第一行包含测试用例的数量。每个测试用例由两行组成,一行指定 N 和 P,另一行指定值列表。
示例: 输入:
1
6 2
1 2 3 4 5 6
输出:
3 4 5 6 1 2
我已经编写了一个函数来进行给定的旋转。我不断收到运行时错误。官方问题定义可以参考https://practice.geeksforgeeks.org/problems/rotate-doubly-linked-list-by-p-nodes/1/。
struct node *rotate(struct node *head){
int num, count=1;
struct node *current, *nnode;
current=head;
printf("\nEnter the number across which you wanna rotate: ");
scanf("%d", &num);
if(num==0){
return;
}
while(count<num && current!=NULL){
current=current->next;
count++;
}
if(current==NULL){
return;
}
nnode=current;
while(current->next!=NULL){
current=current->next;
}
current->next=head;
head->prev=current;
head=nnode->next;
head->prev=NULL;
nnode->next=NULL;
return head;
}
【问题讨论】:
-
输入不清楚。例如第一行数字 1 是什么意思?
-
并显示列表定义。
-
@Vlad:
1可能是“旋转测试次数”,所以后面只有两行。但这应该在问题中说。如果它说2,那么(根据我的假设),会有第二对线,一个是节点数和旋转,另一个是列表中的数字。 -
您不应该在定义为返回值的函数中写入
return;。你需要return NULL;两次才能编译代码。 -
@JonathanLeffler 即使我删除了这些回报;语句,它仍然给我一个运行时错误。
标签: c data-structures linked-list doubly-linked-list