Xóa phần tử rất dễ trong linked list: chỉ cần loại bỏ node (mất tham chiếu). 3 trường hợp:
- Xóa head: gán
head = head.next, mất tham chiếu phần tử đầu - Xóa tail: gán
node.nextcủa node倒数 thứ 2 = null - Xóa giữa:
prevNode.next = node.next(bỏ qua node cần xóa)
Minh họa:

Triển khai
remove(data, position = 0) { if (this.length === 0) { console.log("List is already empty"); return; } this.length--; let currNode = this.head; if (position <= 0) { this.head = this.head.next; } else if (position >= this.length - 1) { while (currNode.next.next != null) { currNode = currNode.next; } currNode.next = null; } else { let iter = 0; while (iter < position) { currNode = currNode.next; iter++; } currNode.next = currNode.next.next; } }
Test:
Ví dụ
let list = new LinkedList(); list.insert(10); list.insert(20); list.insert(30); list.remove(1); list.display(); list.insert(15, 2); list.remove(); list.display();
Kết quả
20 -> 30 -> 30 -> 15 ->