// push(element):向链表尾部添加一个新元素 push(element) { // 创建指针 let current; const node = newNode(element); if (this.head == null) { this.head = node; } else { current = this.head; while (current.next != null) { current = current.next; } // 将其next赋为新元素,建立连接 current.next = node; } this.count++; }
// removeAt(position): 从链表的特定位置移出一个元素 removeAt(position) { // 处理越界值 if (position >= 0 && position <= this.size()) { let current = this.head; // position == 0 if (position === 0) { this.head = current.next; } // position == this.size(),position == 元素中间 else { let previous; for (let i = 0; i < position; i++) { previous = current; current = current.next; } previous.next = current.next; } this.count--; return current.element; } returnundefined; }
// insert(element,postion): 向链表的特定位置插入一个新元素 insert(element, position) { if (position >= 0 && position <= this.size()) { let current = this.head; const node = newNode(element); // position == 0 if (position == 0) { if (this.size() === 0) { this.head = node; } else { node.next = current; this.head = node; } } // position == this.size(),position == 元素中间 else { const previous = this.getElementAt(position - 1); current = previous.next; previous.next = node; node.next = current; } this.count++; returntrue; } returnfalse; }
// getElementAt(index): 返回链表中特定位置的元素。如果链表中不存在这样的元素,则返回undefined getElementAt(index) { if (index >= 0 && index <= this.size()) { let current = this.head; for (let i = 0; i < index && current != null; i++) { current = current.next; } return current; } else { returnundefined; } }
// indexOf(element): 用户输入元素后在链表中进行匹配,找到了就返回索引,否则返回-1 // 使用默认算法无法比对对象类型,只能对原始类型有效 indexOf(element) { let current = this.head; for (let i = 0; i < this.size(); i++) { if (this.equalsFn(current.element, element)) { return i; } current = current.next; } return -1; }
let objString = `${this.head.element}`; let current = this.head.next; for (let i = 1; i < this.size() && current.element != null; i++) { objString = `${objString},${current.element}`; current = current.next; }