[AlgoExpert] Inverted Bisection

Inverted Bisection

  • Time : O(n)
  • Space : O(1)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
class LinkedList {
public:
int value;
LinkedList *next;

LinkedList(int value) {
this->value = value;
this->next = nullptr;
}
};

int getCountOfNodes(LinkedList* head) {
LinkedList* tmp = head;
int count = 0;
while(tmp) {
tmp = tmp->next;
count++;
}
return count;
}

LinkedList *getNthNode(LinkedList* head, int n) {
LinkedList* tmp = head;
while(--n) {
tmp = tmp->next;
}
return tmp;
}

LinkedList* reverse(LinkedList* head) {
LinkedList* dummy = new LinkedList(-1);
dummy->next = head;
LinkedList* runner = head;

while(runner->next) {
LinkedList* nxt = runner->next;
runner->next = nxt->next;
nxt->next = dummy->next;
dummy->next = nxt;
}

return dummy->next;
}

LinkedList *invertedBisection(LinkedList *head) {
int count = getCountOfNodes(head);
if(count == 1) return head;
LinkedList* front = head, *back = nullptr, *middle = nullptr;
LinkedList* frontTail = getNthNode(head, count / 2);

if(count & 1) {
back = frontTail->next->next;
middle = frontTail->next;
} else { //even
back = frontTail->next;
}
frontTail->next = nullptr;
LinkedList* reversedFront = reverse(front);
LinkedList* reversedBack = reverse(back);

if(count & 1) {
middle->next = reversedBack;
head->next = middle;
} else {
head->next = reversedBack;
}

return reversedFront;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/AlgoExpert/inverted-bisection/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.