Skip to content

Commit a8d67f8

Browse files
committed
add shift method to remove first node and edit pop method
1 parent 520aedc commit a8d67f8

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

singly_linkedList/singly_linked_list.js

+20-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,24 @@ class singlyLinkedList {
4646
this.tail = prev;
4747
this.tail.next = null;
4848
this.length--;
49-
return prev;
49+
if (this.length === 0) {
50+
this.head = null;
51+
this.tail = null;
52+
}
53+
return current;
54+
}
55+
shift() {
56+
if (!this.head) {
57+
return undefined;
58+
}
59+
const deleted = this.head;
60+
this.head = this.head.next;
61+
this.length--;
62+
if (this.length === 0) {
63+
this.head = null;
64+
this.tail = null;
65+
}
66+
return deleted;
5067
}
5168
}
5269

@@ -66,4 +83,6 @@ list.push("you");
6683
console.log('traverse list: ');
6784
list.traverse();
6885
console.log('Deleted Node: ', list.pop());
86+
console.log('print List: ', list);
87+
console.log('Shifted Node: ', list.shift());
6988
console.log('print List: ', list);

0 commit comments

Comments
 (0)