Skip to main content

LinkedList getLast() & clear()

本篇介紹 LinkedList 的兩個方法 :

  1. getLast() 取得最後的 node 裡面的 data。
  2. clear() 清除裡面所有的元素。

註記: Java LinkedList 物件有內建這兩個方法,所以不再贅述...

getLast() 期望效果

const myList = new LinkedList();
myList.addFirst("Tom");
myList.addFirst("Mary");
myList.addFirst("Cook");

myList.getLast(); // 回傳 Tom 的 node

JavaScript 解法

寫在 class LinkedLst 內以供之後使用

class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}

class LinkedList {
constructor() {
this.head = null;
}

getLast() {
if (!this.head) {
return null;
}

let node = this.head;
while (node) {
if (!node.next) {
return node;
}
}
node = node.next;
}
}

說明,主要使用 while loop 然後 next ,直到 node.next = null 則回傳該 node。 就會是最後一個元素了。

clear() 期望效果

清空 LinkedList。

JS 實作

比想像中簡單,把第一個 node 清掉,就沒有後面了,因為也沒有 next 了。

clear(){
this.head = null;
}

本篇同時發布於鐵人賽