File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ // solve by recursion
2
+
3
+ /* *
4
+ * Definition for singly-linked list.
5
+ * struct ListNode {
6
+ * int val;
7
+ * ListNode *next;
8
+ * ListNode(int x) : val(x), next(NULL) {}
9
+ * };
10
+ */
11
+ class Solution {
12
+ public:
13
+ ListNode *reverse (ListNode *head)
14
+ {
15
+ ListNode *ptr=head,*tmp=NULL ;
16
+ while (ptr)
17
+ {
18
+ ListNode *nxt=ptr->next ;
19
+ ptr->next =tmp;
20
+ tmp=ptr;
21
+ ptr=nxt;
22
+ }
23
+ return tmp;
24
+ }
25
+ ListNode *reverseKGroup (ListNode *head, int k) {
26
+ // Start typing your C/C++ solution below
27
+ // DO NOT write int main() function
28
+ if (head==NULL )return head;
29
+ ListNode *ptr=head;
30
+ int c=k;
31
+ while (--c&&ptr)
32
+ {
33
+ ptr=ptr->next ;
34
+ }
35
+ if (!ptr)return head;
36
+ ListNode *nxt=ptr->next ,*tmp=head;
37
+ ptr->next =NULL ;
38
+ head=reverse (head);
39
+ tmp->next =reverseKGroup (nxt,k);
40
+ return head;
41
+
42
+ }
43
+ };
You can’t perform that action at this time.
0 commit comments