第16题 reverse every K elements of a linked list

来源:互联网 发布:智能社javascript视频 编辑:程序博客网 时间:2024/06/06 02:26

Write a program to reverse every K elements of a linked list.

Example: K = 3


1->2->3->4->5->6->NULL


output: 3->2->1->6->5->4-NULL


struct node *reverse (struct node *head, int k){    struct node* current = head;    struct node* next;    struct node* result = NULL;    int count = 0;     while (current != NULL && count < k)    {         next = current->next;         current->next = result;         result = current;         current = next;         count++;    }    if(next != NULL)    {         head->next = reverse(next, k);     }    return result;}


原创粉丝点击