I have written the code, can anyone optimize it? If u need the full code then comment, I will do it. Help me out. I did this because I didn't get the code online for doing this in a recursive way.
我写过代码,有人可以优化吗?如果你需要完整的代码然后评论,我会这样做。帮帮我。我这样做是因为我没有在线获取代码以递归方式执行此操作。
n reversekNode(n head,n pre,n frst,int i,int m){
if(head!=NULL){
if(i<m-1){
n nxt = head->next;
head->next = pre;
if(i==0)
frst = head;
return reversekNode(nxt,head,frst,i+1,m);
}else{
n nn = head->next;
head->next=pre;
if(head->next!=NULL){
frst->next = reversekNode(nn,head,NULL,0,m);
}
return head;
}
}
}
1 个解决方案
#1
1
The simplest code I can think of to recursively reverse the first k
items in a list is this
我能想到的最简单的代码是递归地反转列表中的前k项是这样的
Node *reverseList(Node *a, Node *b, int k)
{
if (b == NULL || k <= 1)
return a;
Node *head = reverseList(b, b->next, k-1);
Node *temp = b->next;
b->next = a;
a->next = temp;
return head;
}
It should be called like this
它应该像这样调用
if (head != NULL)
head = reverseList(head, head->next, k);
#1
1
The simplest code I can think of to recursively reverse the first k
items in a list is this
我能想到的最简单的代码是递归地反转列表中的前k项是这样的
Node *reverseList(Node *a, Node *b, int k)
{
if (b == NULL || k <= 1)
return a;
Node *head = reverseList(b, b->next, k-1);
Node *temp = b->next;
b->next = a;
a->next = temp;
return head;
}
It should be called like this
它应该像这样调用
if (head != NULL)
head = reverseList(head, head->next, k);