Skip to content

Commit bff67ec

Browse files
committed
Add 'Reverse Nodes in k-Group' solution.
1 parent 913502a commit bff67ec

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Reverse_Nodes_in_kGroup .cpp

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
Given a linked list, reverse the nodes of a linked list k at a time and
3+
return its modified list.
4+
If the number of nodes is not a multiple of k then left-out nodes in the
5+
end should remain as it is.
6+
You may not alter the values in the nodes, only nodes itself may be
7+
changed.
8+
9+
Only constant memory is allowed.
10+
11+
For example,
12+
Given this linked list: 1->2->3->4->5
13+
For k = 2, you should return: 2->1->4->3->5
14+
For k = 3, you should return: 3->2->1->4->5
15+
*/
16+
17+
/**
18+
* Definition for singly-linked list.
19+
* struct ListNode {
20+
* int val;
21+
* ListNode *next;
22+
* ListNode(int x) : val(x), next(NULL) {}
23+
* };
24+
*/
25+
class Solution {
26+
public:
27+
// Reverse sub-linked list which starts from head node.
28+
// preHead's next node is the head node of the reversed sub-linked list.
29+
// The function returns the tail node of the reversed sub-linked list.
30+
ListNode *subReverse(ListNode *preHead, ListNode *head, int cnt) {
31+
if (cnt == 0) {
32+
preHead->next = head;
33+
} else {
34+
subReverse(preHead, head->next, cnt - 1)->next = head;
35+
}
36+
return head;
37+
}
38+
39+
ListNode *reverseKGroup(ListNode *head, int k) {
40+
if (head == NULL || k <= 1) return head;
41+
42+
ListNode *newHead = new ListNode(-1);
43+
newHead->next = head;
44+
ListNode *st = newHead, *en, *tail;
45+
while (st != NULL) {
46+
// Check whether last nodes is enough to be reversed.
47+
int cnt = 0;
48+
en = st->next;
49+
while (cnt < k && en != NULL) {
50+
++cnt;
51+
en = en->next;
52+
}
53+
54+
if (cnt < k) break;
55+
tail = subReverse(st, st->next, k-1);
56+
tail->next = en;
57+
st = tail;
58+
}
59+
head = newHead->next;
60+
delete newHead;
61+
return head;
62+
}
63+
};

0 commit comments

Comments
 (0)