Skip to content

Commit fe00e99

Browse files
committed
Create Reverse Nodes in k-Group.cpp
1 parent 50d05cf commit fe00e99

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Reverse Nodes in k-Group.cpp

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
};

0 commit comments

Comments
 (0)