本篇的完整程式碼在這裡
距離30天期滿倒數5天,雖然此系列一定超過30天啦哈哈
不過希望接下來5天不要開天窗,加油~
push & pop 的功用為在 Array 末端新增元素 & 移除元素
而 shift & unShift 則在 Array 開頭新增元素 & 移除元素
使用上篇的結構繼續新增 method
The Shift
method of array is to remove the first element from the array and returns that removed element.
Shift
跟 Pop
相反,會移除掉 array 內第一個元素,並回傳該被移除的元素
...
shift() {
if (!this.head) {
return null;
} else {
let temp = this.head;
this.length === 1
? (this.head = null)
: (this.head = this.head.next);
this.length--;
return temp;
}
}
...
The UnShift
method of array is to add the element from beginning of the array and returns the new length of the array.
UnShift
跟 Push
相反,是在 array 開頭新增元素並回傳新的 array length
...
unshift(value) {
if (!this.head) {
this.head = new Node(value);
} else {
let newNode = new Node(value);
let temp = this.head;
this.head = newNode;
this.head.next = temp;
}
this.length++;
return this.length;
}
...
一樣來試試看 shift 跟 unshift
nameLinkedList.shift(); // remove Node which value is "Ted"
nameLinkedList.unshift("Gleen"); // add Node which value is "Gleen" from the beginning
這時候可以看到 first Node 被 shift 移除且被 return
而 unshift 添加 Node 到 Linked List 開頭處
singly linked list pop and shift
https://medium.com/@baruchphillips/singly-linked-list-pop-and-shift-a01a0de146b9