问题
https://leetcode.com/problems/reverse-nodes-in-k-group/
代码
先用pre 记录要翻转段之前的指针。
H->1->2->3->4->Null
假设要翻转1, 2, 3;
pre 指向H,fin指向1, prt指向2
将2 插入H后面,
ptr移向3,
将3插入H后面,
。。。。
/**
* 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 (k<2) return head;
ListNode Head(0);
Head.next = head;
ListNode* pre = &Head;
while(1){
int cnt =0;
ListNode* last = pre;
while(cnt<=k&&last) last= last->next, cnt++;
if (cnt<=k) break;
ListNode * fin = pre->next;
ListNode * ptr = fin->next;
while(ptr!= last)
{
fin->next = ptr->next;
ptr->next = pre->next;
pre->next = ptr;
ptr = fin->next;
}
pre = fin;
}
return Head.next;
}
};