[leetcode] 【链表】25. Reverse Nodes in k-Group

来源:互联网 发布:网络投诉管理办法 编辑:程序博客网 时间:2024/06/05 15:38

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


题意

一个链表,每k个节点为一部分,然后这k个节点逆序翻转,如果最后剩余不足k个节点,那么保持原来的顺序,

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


题解

从头开始遍历,每到k个便翻转,不够k个就跳出。
翻转方法参考92题
92. Reverse Linked List II
http://blog.csdn.net/u014654002/article/details/51538495

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseKGroup(ListNode* head, int k) {        if(head==NULL||head->next==NULL||k<2) return head;        ListNode newhead(-1);        newhead.next=head;        for(ListNode *prev=&newhead,*end=head;end;end=prev->next)        {            for(int i=1;i<k&&end;i++)                end=end->next;            if(end==NULL) break;            prev=reverse(prev,prev->next,end);        }        return newhead.next;    }    ListNode* reverse(ListNode *prev,ListNode *begin,ListNode *end)    {        ListNode* temp=end->next;        for(ListNode *p=begin,*cur=p->next,*next=cur->next;cur!=temp;        p=cur,cur=next,next=next? next->next:NULL)            cur->next=p;        begin->next=temp;        prev->next=end;        return begin;    }};




1 0