题目连接:Leetcode 025 Reverse Nodes in k-Group
解题思路:每次将k个结点当成一个子链表,进行翻转。每个翻转后的子链表收尾拼接在一起。
/**
* 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) {
ListNode first = ListNode(0);
ListNode* ans = &first;
ListNode* move = ans;
while (head != NULL) {
int t = k;
ListNode* count = head;
while (t && count != NULL) {
count = count->next;
t--;
}
if (t) {
move->next = head;
break;
}
ListNode* last = NULL;
for (int i = 0; i < k && head != NULL; i++) {
ListNode* tmp = head->next;
head->next = last;
last = head;
head = tmp;
}
move->next = last;
while (move->next != NULL) move = move->next;
}
return ans->next;
}
};