Skip to content

Commit f114696

Browse files
committed
feat: add unshift, get, set, insert and remove methods to the singlyLinkedList
1 parent ba0ae33 commit f114696

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

LinkedList/singlyLinkedList.js

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,69 @@ class SinglyLinkedList {
6161

6262
return tempHead;
6363
}
64+
65+
unshift(value) {
66+
var newNode = new Node(value);
67+
68+
if (!this.head) {
69+
this.head = newNode;
70+
this.tail = this.head;
71+
} else {
72+
newNode.next = this.head;
73+
this.head = newNode;
74+
}
75+
76+
this.length++;
77+
return this;
78+
}
79+
80+
get(index) {
81+
if (index < 0 || index >= this.length) return null;
82+
var counter = 0;
83+
var current = this.head;
84+
85+
while (counter !== index) {
86+
current = current.next;
87+
counter++;
88+
}
89+
90+
return current;
91+
}
92+
93+
set(index, value) {
94+
var node = this.get(index);
95+
if (!node) return false;
96+
node.value = value;
97+
98+
return true;
99+
}
100+
101+
insert(index, value) {
102+
if (index < 0 || index > this.length) return false;
103+
if (index === this.length) return !!this.push(value);
104+
if (index === 0) return !!this.unshift(value);
105+
var newNode = new Node(value);
106+
var prevNode = this.get(index - 1);
107+
var temp = prevNode.next;
108+
prevNode.next = newNode;
109+
newNode.next = temp;
110+
this.length++;
111+
112+
return true;
113+
}
114+
115+
remove(index) {
116+
if (index < 0 || index > this.length) return undefined;
117+
if (index === this.length - 1) this.pop();
118+
if (index === 0) this.shift();
119+
var prevNode = this.get(index - 1);
120+
var removedNode = prevNode.next;
121+
122+
prevNode.next = removedNode.next;
123+
124+
this.length--;
125+
return removedNode;
126+
}
64127
}
65128

66129
var list = new SinglyLinkedList();

0 commit comments

Comments
 (0)