Skip to content

Commit c459eda

Browse files
committed
add remove method to singly_linkedList
1 parent 570780b commit c459eda

File tree

1 file changed

+35
-15
lines changed

1 file changed

+35
-15
lines changed

Diff for: singly_linkedList/singly_linked_list.js

+35-15
Original file line numberDiff line numberDiff line change
@@ -112,17 +112,35 @@ class singlyLinkedList {
112112
}
113113
if (index === this.length) {
114114
this.push(newNode);
115-
} else if (index === 0) {
115+
return true;
116+
}
117+
if (index === 0) {
116118
this.unshift(newNode);
117-
} else {
118-
const prev = this.get(index - 1);
119-
const temp = prev.next;
120-
prev.next = newNode;
121-
newNode.next = temp;
119+
return true;
122120
}
121+
const prev = this.get(index - 1);
122+
const temp = prev.next;
123+
prev.next = newNode;
124+
newNode.next = temp;
123125
this.length++;
124126
return true;
125127
}
128+
remove(index) {
129+
if (index < 0 || index >= this.length) {
130+
return undefined;
131+
}
132+
if (index === this.length - 1) {
133+
return this.pop();
134+
}
135+
if (index === 0) {
136+
this.shift();
137+
}
138+
const prev = this.get(index - 1);
139+
const removed = prev.next;
140+
prev.next = removed.next;
141+
this.length--;
142+
return removed;
143+
}
126144
}
127145

128146
// const first = new Node("hi");
@@ -138,15 +156,17 @@ list.push("hadis");
138156
list.push("how");
139157
list.push("are");
140158
list.push("you");
141-
console.log('traverse list: ');
159+
console.log("traverse list: ");
142160
list.traverse();
143-
console.log('Deleted Node: ', list.pop());
144-
console.log('print List: ', list);
145-
console.log('Shifted Node: ', list.shift());
146-
console.log('print List: ', list);
147-
list.unshift('welcome');
148-
console.log('print List: ', list);
161+
console.log("Deleted Node: ", list.pop());
162+
console.log("print List: ", list);
163+
console.log("Shifted Node: ", list.shift());
164+
console.log("print List: ", list);
165+
list.unshift("welcome");
166+
console.log("print List: ", list);
149167
console.log(list.get(0));
150168
console.log(list.get(3));
151-
list.set('where ', 2);
152-
list.insert('test', 2);
169+
list.set("where ", 2);
170+
list.insert("test", 2);
171+
list.remove(1);
172+
list.traverse();

0 commit comments

Comments
 (0)