[InterviewBit] Reverse Alternate K Nodes

Reverse Alternate K Nodes

  • Time :
  • Space :
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* cut(ListNode* A, int k) {
ListNode* runner = A;
for(int i = 0; i < k and runner->next; i++) runner = runner->next;
return runner;
}
ListNode* reverse(ListNode* node) {
ListNode* dummy = new ListNode(-1);
ListNode* runner = node;
while(runner) {
ListNode* nxt = runner->next;
runner->next = dummy->next;
dummy->next = runner;
runner = nxt;
}
return dummy->next;
}
ListNode* Solution::solve(ListNode* A, int B) {
ListNode* dummy = new ListNode(-1);
dummy->next = A;
ListNode* tail = dummy;
while(tail) {
ListNode* half = cut(tail, B);
ListNode* safe = half->next;
half->next = NULL;
ListNode* rev = reverse(tail->next);
tail->next = rev;
while(tail->next) tail = tail->next;
tail->next = safe;
for(int i = 0; i < B and tail; i++) tail = tail->next;
}

return dummy->next;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/31/PS/interviewbit/reverse-alternate-k-nodes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.