“我们先来看看它们的职责”
- push(element):向链表尾部添加一个新元素。
- insert(element, position):向链表的特定位置插入一个新元素。
- getElementAt(index):返回链表中特定位置的元素。如果链表中不存在这样的元素,则返回undefined。
- remove(element):从链表中移除一个元素。
- indexOf(element):返回元素在链表中的索引。如果链表中没有该元素则返回-1。
- removeAt(position):从链表的特定位置移除一个元素。
- isEmpty():如果链表中不包含任何元素,返回true,如果链表长度大于0则返回false。
- size():返回链表包含的元素个数,与数组的length属性类似。
- toString():返回表示整个链表的字符串。由于列表项使用了Node类,就需要重写继承自JavaScript对象默认的toString方法,让其只输出元素的值。
export function defaultEquals(a, b) {
return a === b;
}
export class Node {
constructor(element) {
this.element = element;
this.next = undefined;
}
}
export default class LinkedList {
constructor(equalsFn = defaultEquals) {
this.count = 0; // {2}
this.head = undefined; // {3}
this.equalsFn = equalsFn; // {4}
}
push(element) {
const node = new Node(element); // {1}
let current; // {2}
if (this.head == null) { // {3}
this.head = node;
} else {
current = this.head; // {4}
while (current.next != null) { // {5} 获得最后一项
current = current.next;
}
// 将其next赋为新元素,建立链接
current.next = node; // {6}
}
this.count++; // {7}”
}
removeAt(index) {
// 检查越界值
if (index >= 0 && index < this.count) { // {1}
let current = this.head; // {2}
// 移除第一项
if (index === 0) { // {3}
this.head = current.next;
} else {
let previous; // {4}
for (let i = 0; i < index; i++) { // {5}
previous = current; // {6}
current = current.next; // {7}
}
// 将previous与current的下一项链接起来:跳过current,从而移除它
previous.next = current.next; // {8}
}
this.count--; // {9}
return current.element;
}
return undefined; // {10}
}
getElementAt(index) {
if (index >= 0 && index <= this.count) { // {1}
let node = this.head; // {2}
for (let i = 0; i < index && node != null; i++) { // {3}
node = node.next;
}
return node; // {4}
}
return undefined; // {5}
}
insert(element, index) {
if (index >= 0 && index <= this.count) { // {1}
const node = new Node(element);
if (index === 0) { // 在第一个位置添加
const current = this.head;
node.next = current; // {2}
this.head = node;
} else {
const previous = this.getElementAt(index - 1); // {3}
const current = previous.next; // {4}
node.next = current; // {5}
previous.next = node; // {6}
}
this.count++; // 更新链表的长度
return true;
}
return false; // {7}
}
indexOf(element) {
let current = this.head; // {1}
for (let i = 0; i < this.count && current != null; i++) { // {2}
if (this.equalsFn(element, current.element)) { // {3}
return i; // {4}
}
current = current.next; // {5}
}
return -1; // {6}
}
remove(element) {
const index = this.indexOf(element);
return this.removeAt(index);
}
size() {
return this.count;
}
isEmpty() {
return this.size() === 0;
}
getHead() {
return this.head;
}
toString() {
if (this.head == null) { // {1}
return '';
}
let objString = `${this.head.element}`; // {2}
let current = this.head.next; // {3}
for (let i = 1; i < this.size() && current != null; i++) { // {4}
objString = `${objString},${current.element}`;
current = current.next;
}
return objString; // {5}
}
}