使用js实现一个链表
class linkNode {
constructor(val, next) {
this.val = val;
this.next = next;
}
}
class linkedList {
constructor() {
this._size = 0;
this._head = null;
this._tail = null;
}
addAtHead(val) {
const node = new linkNode(val, this._head);
this._head = node;
this._size++;
!this._tail && (this._tail = node);
}
addAtTail(val) {
const node = new linkNode(val, null);
if (this._tail) {
this._tail.next = node;
} else {
this._head = node;
}
this._size++;
this._tail = node;
}
addAtIndex(index, val) {
if (index < 0 || index >= this._size) {
throw "addAtIndex()索引不存在";
}
let lest = null;
let count = 0;
while (count <= index - 1) {
lest = lest ? lest.next : this._head;
count++;
}
let current = lest ? lest.next : this._head;
const node = new linkNode(val, current);
!lest ? (this._head = node) : (lest.next = node);
!current && (this._tail = node);
this._size++;
}
getByIndex(index) {
if (index < 0 || index >= this._size) {
throw "getByIndex()索引不存在";
}
let currentNode = this._head;
let count = 0;
while (count <= index - 1) {
currentNode = currentNode.next;
count++;
}
return currentNode;
}
deleteAtIndex(index) {
if (index < 0 || index >= this._size) {
throw "getByIndex()索引不存在";
}
let lest = null;
let count = 0;
while (count <= index - 1) {
lest = lest ? lest.next : this._head;
count++;
}
let current = lest ? lest.next : this._head;
let next = current ? current.next : this._head;
lest ? (lest.next = next) : (this._head = next);
!next && (this._tail = next);
this._size--;
}
}
const list = new linkedList();
list.addAtHead(2);
list.addAtHead(5);
list.addAtHead(100);
list.addAtHead(5200);
list.addAtIndex(3, 111);
console.log(list);