[leetcode-25]Reverse Nodes in k-Group(C)

来源:互联网 发布:塞尔维亚 知乎 编辑:程序博客网 时间:2024/04/29 15:55

问题描述:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

分析:这道题列为hard,我觉得还是蛮奇怪的。这道题就是将一个链表以k为组进行分割,然后在每个组里进行调转。

代码如下:12ms

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* reverseGroup(struct ListNode* head,int k,struct ListNode** nextHead){    int i;    struct ListNode *prev = NULL,*current=head,*next;    for(i = 0;i<k;i++){        next = current->next;        current->next = prev;        prev = current;        current = next;    }    *nextHead = current;    return prev;}struct ListNode* reverseKGroup(struct ListNode* head, int k) {    int length = 0;    struct ListNode *currentHead = head;    struct ListNode *nextHead = NULL;    struct ListNode *tail = NULL;    struct ListNode *tmpHead = head;    while(tmpHead){        length++;        tmpHead = tmpHead->next;    }    int i;    if(length<k)        return head;    if(k==1)        return head;    for(i = k-1;i<length;i=i+k){        tmpHead = reverseGroup(currentHead,k,&nextHead);        if(!tail){//第一组            head = tmpHead;            tail = currentHead;        }        else{            tail->next = tmpHead;            tail = currentHead;        }        currentHead = nextHead;    }    tail->next = currentHead;    return head;}
0 0
原创粉丝点击