[AlgoExpert] Rearrange Linked List

Rearrange Linked List

  • 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
using namespace std;

class LinkedList {
public:
int value;
LinkedList *next;

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

LinkedList *rearrangeLinkedList(LinkedList *head, int k) {
LinkedList *smallerDummy = new LinkedList(-1), *smallerTail = smallerDummy;
LinkedList *biggerDummy = new LinkedList(-1), *biggerTail = biggerDummy;
LinkedList *kDummy = new LinkedList(-1), *kTail = kDummy;

while(head) {
LinkedList* nxt = head->next;
head->next = nullptr;
if(head->value < k) {
smallerTail->next = head;
smallerTail = smallerTail->next;
} else if(head->value == k) {
kTail->next = head;
kTail = kTail->next;
} else {
biggerTail->next = head;
biggerTail = biggerTail->next;
}
head = nxt;
}

LinkedList* tail = smallerTail;
if(kDummy != kTail) {
tail->next = kDummy->next;
tail = kTail;
}
if(biggerDummy != biggerTail) {
tail->next = biggerDummy->next;
}

return smallerDummy->next;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/rearrange-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.