-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLeetCode#24.cc
46 lines (45 loc) · 1.15 KB
/
LeetCode#24.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* reverseList(ListNode* head, int k){
ListNode* pre = NULL;
ListNode* cur = head;
int cnt = 0;
while(++cnt <= k && cur!=NULL){cur=cur->next;}
if(cnt<=k) return head;
cur = head;
cnt=0;
while(cnt++ < k && cur!=NULL){
ListNode* t = cur->next;
cur->next = pre;
pre = cur;
cur = t;
}
head->next = cur;
return pre;
}
ListNode* dfs(ListNode* node, int k, int num){
if(node==NULL) return NULL;
ListNode* t = dfs(node->next,k,num+1);
node->next = t;
if(num%k==1){
return reverseList(node,k);
}
else return node;
}
public:
ListNode *reverseKGroup(ListNode *head, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head==NULL) return NULL;
if(k<=1) return head;
return dfs(head,k,1);
}
};