[AlgoExpert] Linked List Construction

Linked List Construction

  • Space : O(n)
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using namespace std;

class Node {
public:
int value;
Node *prev;
Node *next;

Node(int value);
};

// Feel free to add new properties and methods to the class.
class DoublyLinkedList {
public:
Node *head;
Node *tail;
unordered_map<int, unordered_set<Node*>> mp;

DoublyLinkedList() {
head = nullptr;
tail = nullptr;
}

void setHead(Node *node) { //O(1)
if(containsNodeWithValue(node->value)) {
remove(node);
}
mp[node->value].insert(node);
if(head) {
head->prev = node;
node->next = head;
} else tail = node;
head = node;
node->prev = nullptr;
}

void setTail(Node *node) { //O(1)
if(containsNodeWithValue(node->value)) {
remove(node);
}
mp[node->value].insert(node);
if(tail) {
tail->next = node;
node->prev = tail;
} else head = node;
tail = node;
tail->next = nullptr;
}

void insertBefore(Node *node, Node *nodeToInsert) { // O(1)
if(containsNodeWithValue(nodeToInsert->value)) {
remove(nodeToInsert);
}
if(node == head)
setHead(nodeToInsert);
else {
mp[nodeToInsert->value].insert(nodeToInsert);
nodeToInsert->prev = node->prev;
nodeToInsert->next = node;
node->prev->next = nodeToInsert;
node->prev = nodeToInsert;
}
}

void insertAfter(Node *node, Node *nodeToInsert) { // O(1)
if(containsNodeWithValue(nodeToInsert->value)) {
remove(nodeToInsert);
}
if(node == tail)
setTail(nodeToInsert);
else {
mp[nodeToInsert->value].insert(nodeToInsert);
nodeToInsert->next = node->next;
nodeToInsert->prev = node;
node->next->prev = nodeToInsert;
node->next = nodeToInsert;
}
}

void insertAtPosition(int position, Node *nodeToInsert) { // O(position)
Node* tmp = head;
while(--position)
tmp = tmp->next;
insertBefore(tmp, nodeToInsert);
}

void removeNodesWithValue(int value) { //O(number of value nodes)
if(containsNodeWithValue(value)) {
while(mp[value].size()) {
remove(*begin(mp[value]));
}
}
}

void remove(Node *node) { //O(1)
mp[node->value].erase(node);
if(node->prev)
node->prev->next = node->next;
if(node->next)
node->next->prev = node->prev;
if(node == head)
head = head->next;
if(node == tail)
tail = tail->prev;
node->prev = nullptr;
node->next = nullptr;
}

bool containsNodeWithValue(int value) { //O(1)
return mp[value].size();
}
};

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