1 class Solution {
2 public:
3 ListNode *reverseKGroup(ListNode *head, int k) {
4 // IMPORTANT: Please reset any member data you declared, as
5 // the same Solution instance will be reused for each test case.
6 if (k<=1 || head == NULL)
7 return head;
8 ListNode * itr =head;
9 ListNode * lastTail = NULL;
10 while (itr != NULL){
11 ListNode * nextItr = NULL;
12 ListNode * curHead = NULL, *curTail =NULL;
13 for (int i=0; i<k && itr!=NULL; i++){
14 nextItr = itr->next;
15 if (i==0)
16 curHead = itr;
17 if (i==k-1)
18 curTail = itr;
19 itr = nextItr;
20 }
21 if (curTail != NULL){
22 ListNode * tmp = curHead->next, *last=curHead;
23 for (int j=0; j<k-1; j++){
24 ListNode * nextTmp = tmp->next;
25 tmp->next = last;
26 last = tmp;
27 tmp = nextTmp;
28 }
29 if (curHead == head)
30 head = curTail;
31 if (lastTail != NULL)
32 lastTail->next = curTail;
33 lastTail = curHead;
34 lastTail->next = NULL;
35 }
36 else {
37 if (lastTail!=NULL)
38 lastTail->next = curHead;
39 break;
40 }
41 }
42 return head;
43 }
44 };