0

我是新的 ds。我正在尝试这个问题 - 给定一个链表,编写一个函数以有效的方式反转每个备用 k 节点(其中 k 是函数的输入)。给出算法的复杂性。我的代码给了我分段错误。帮助!

‎</p>

struct node* func(struct node* head, int k)
{
    struct node* run, *list1;
    run =head->next;
    list1=head;

    int count =0;

    struct node *list2=NULL;

while(list1!=NULL && count++<k)
{
    list1->next=list2;
    list2=list1;
    list1=run;
    run=list1->next;
}

head=list2;

while(list2->next!=NULL && list2!=NULL)
    list2=list2->next;

list2->next=list1;

while(list1!=NULL && count++<k-1)
    list1=list1->next;

if(list1!=NULL)
    list1->next=func( head, k);
    return head;
}
4

1 回答 1

0
struct node* func_aux(struct node* head, struct node* rev, int k){
    struct node* next;
    if(k == 0 || head == NULL)
        return rev;
    next = head->next;
    head->next = rev;
    return func_aux(next, head, --k);
}

struct node* func(struct node* head, int k){
    struct node* kth_node;
    int i=0;
    for(kth_node=head;kth_node;kth_node=kth_node->next,++i){
        if(k==i)break;
    }
    return func_aux(head, kth_node, k);
}
于 2012-08-10T15:41:20.797 回答