【问题标题】:Optimal soltuion for reversing k nodes using recursion in linked list链表中使用递归反转k个节点的最优解
【发布时间】:2018-07-28 15:01:40
【问题描述】:

我已经写好了代码,谁能优化一下?如果你需要完整的代码然后评论,我会做的。帮帮我。我这样做是因为我没有在线获取用于以递归方式执行此操作的代码。

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;
        }
    }
}

【问题讨论】:

  • 对什么最优化?具体一点。

标签: c recursion data-structures


【解决方案1】:

我能想到的递归反转列表中第一个 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;
}

应该这样称呼

if (head != NULL)
    head = reverseList(head, head->next, k);

【讨论】:

  • Bro k u 没有增加 k 值
猜你喜欢
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 2016-08-08
  • 2020-12-25
  • 2016-07-09
  • 2022-01-18
  • 2020-07-22
相关资源
最近更新 更多