25.Reverse Nodes in k-Group

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

Subscribe to see which companies asked this question

 思路:递归。首先找到第k+1个节点,也就是这一段需要翻转的链表的尾部相连的那个节点。如果找不到第k+1个节点,说明这一段链表长度不足k,无需进行翻转。在找到第k+1个节点的情况下,首先递归求后面直接相连的链表翻转之后的的头结点。然后再将这个头结点之前的需要翻转的链表节点逐个重新连接,进行翻转。最终,返回翻转之后的链表的头结点。

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode *cur=head;
        int count=0;
        //找到第k+1个节点
        while(cur&&count!=k){
            cur=cur->next;
            count++;
        }
        //找到了第k+1个节点,开始进行翻转
        if(count==k){
            //下一段链表翻转之后的头结点
            cur =reverseKGroup(cur,k);
            while(count-->0){
                ListNode *temp =head->next;
                head->next=cur;//将head指向cur
                cur=head;//将cur向前移动一位
                head=temp;//将head向后移动一位
            }
            head=cur;//此时,头结点变成原来的尾部节点
        }
        return head;//返回head
    }
};

 

posted @ 2016-03-15 23:42  ZHOU YANG  阅读(346)  评论(0编辑  收藏  举报