-
Notifications
You must be signed in to change notification settings - Fork 288
/
Copy pathAC_recursive_n.cpp
53 lines (44 loc) · 1.09 KB
/
AC_recursive_n.cpp
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
47
48
49
50
51
52
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_recursive_n.cpp
* Create Date: 2015-01-15 20:45:27
* Descripton: Count k nodes and recursive
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
// 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 || !(head->next) || k < 2)
return head;
// count k nodes
ListNode *nextgp = head;
for (int i = 0; i < k; i++)
if (nextgp)
nextgp = nextgp->next;
else
return head;
// reverse
ListNode *prev = NULL, *cur = head, *next = NULL;
while (cur != nextgp) {
next = cur->next;
if (prev)
cur->next = prev;
else
cur->next = reverseKGroup(nextgp, k);
prev = cur;
cur = next;
}
return prev;
}
};
int main() {
return 0;
}