C 链表中用递归法求k结点反向的最优解
我已经写了代码,有人能优化它吗?如果你需要完整的代码,然后评论,我会这样做。帮帮我。我这样做是因为我没有在线获取以递归方式执行此操作的代码C 链表中用递归法求k结点反向的最优解,c,recursion,data-structures,C,Recursion,Data Structures,我已经写了代码,有人能优化它吗?如果你需要完整的代码,然后评论,我会这样做。帮帮我。我这样做是因为我没有在线获取以递归方式执行此操作的代码 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)
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;
}
}
}
n反向节点(n头,n前,n首,int i,int m){
if(head!=NULL){
如果(不精确;
head->next=pre;
如果(i==0)
frst=头;
返回反向节点(nxt,head,first,i+1,m);
}否则{
n nn=头部->下一步;
head->next=pre;
如果(头部->下一步!=NULL){
frst->next=反向节点(nn,head,NULL,0,m);
}
回流头;
}
}
}
我能想到的递归反转列表中第一个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;
}
关于什么是最优的?具体来说。Bro k u没有增加k值
if (head != NULL)
head = reverseList(head, head->next, k);