[InterviewBit] Even Reverse

Even Reverse

  • 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* reverse(ListNode* A) {
ListNode* dummy = new ListNode(-1);
ListNode* runner = A;
while(runner) {
ListNode* nxt = runner->next;
runner->next = dummy->next;
dummy->next = runner;
runner = nxt;
}

return dummy->next;
}
ListNode* Solution::solve(ListNode* A) {
bool fl = true;
ListNode* odd = new ListNode(-1);
ListNode* even = new ListNode(-1);
ListNode* otail = odd, *etail = even;
ListNode* runner = A;
while(runner) {
if(fl) {
otail->next = runner;
otail = otail->next;
} else {
etail->next = runner;
etail = etail->next;
}
runner = runner->next;
otail->next = etail->next = NULL;
fl = !fl;
}
ListNode* rev = reverse(even->next);
ListNode* res = new ListNode(-1);
runner = res;
odd = odd->next;
fl = true;
while(odd or rev) {
if(fl) {
runner->next = odd;
odd = odd->next;
} else {
runner->next = rev;
rev = rev->next;
}
runner = runner->next;
fl = !fl;
}
return res->next;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/01/PS/interviewbit/even-reverse/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.