链表结构
链表存储有序的元素集合,但不同于数组,链表中的元素在内存中并不是连续放置的。每个 元素由一个存储元素本身的节点和一个指向下一个元素的引用(也称指针或链接)组成。
用 js 实现链表结构
class node {
constructor(elemernt) {
this.elemernt = elemernt;
this.next = null;
}
}
// 创建一个链表
class linkedList {
constructor() {
this.head = null;
this.length = 0;
}
// 追加一个元素
append(element) {
const node = new node(element);
let curret = null;
if (this.head == null) {
this.head = node;
} else {
curret = this.head;
while (curret.next) {
curret = curret.next;
}
curret.next = node;
}
this.length++;
}
// 任意位置插入元素
insert(position, element) {
if (position >= 0 && position <= this.length) {
const node = new node(element);
let precious = null;
let curret = this.head;
let index = 0;
if (position === 0) {
curret = node;
} else {
while (index++ < position) {
precious = curret;
curret = curret.next;
}
precious.next = node;
node.next = curret;
}
this.length++;
}
}
// 删除指定位置的元素
removeEl(position){
if(position >= 0 && position <= this.length){
let precious = null;
let curret = this.head;
let index = 0;
if(position === 0){
this.head = curret.next
}else{
while(index++ < position){
precious = curret;
curret = curret.next;
}
precious.next = curret.next
}
this.length --
return curret
}
return null
}
// 寻找元素下标
findElement(element){
let curret = this.head;
let index = -1;
if(currrt === element){
return -1
}else{
while(curret.next === element){
index++
curret = curret.next
}
return index
}
}
// 删除指定坐标元素
remove(element){
const index = this.indexOf(element)
removeEl(index)
}
// 判断数组是否为空
isEmpty(){
return !this.length
}
size(){
return this.length
}
}