iT邦幫忙

2024 iThome 鐵人賽

DAY 25
0
佛心分享-IT 人自學之術

演算法與資料結構入門:30天基礎學習之旅系列 第 25 篇

How to Implement a Linked List with Shift/UnShift methods in javascript-day 25

  • 分享至 

  • xImage
  •  

本篇的完整程式碼在這裡

距離30天期滿倒數5天,雖然此系列一定超過30天啦哈哈
不過希望接下來5天不要開天窗,加油~

push & pop 的功用為在 Array 末端新增元素 & 移除元素
而 shift & unShift 則在 Array 開頭新增元素 & 移除元素
使用上篇的結構繼續新增 method

Shift method

The Shift method of array is to remove the first element from the array and returns that removed element.

Shift 跟 Pop 相反,會移除掉 array 內第一個元素,並回傳該被移除的元素

shift method 執行的內容:

  • 如果 Linked List 內無 Node,直接 return null
  • 如果 Linked List 內只有一個 Node,this.length-- , this.next=null
  • 如果 Linked List 內有複數個 Node,this.length-- , 將 this.head point to this.head.next(head 移動到下一個點)
...
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;
    }
}
...

UnShift method

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 method 執行的內容:

  • 如果 Linked List 內無 Node,this.head point to new node
  • 如果 Linked List 內有 Node,先把 oldHead 用 temp 存起來,再將 new node set to this.head,並將 new node 的 next point to temp
  • Linked List 的 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


上一篇
How to Implement a Linked List with Push/Pop methods in javascript-day 24
下一篇
Implement a Linked List with insertAt/removeAt/get method in javascript-day 26
系列文
演算法與資料結構入門:30天基礎學習之旅 共 30 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言