JS数据结构与算法--双向链表
2024-10-20 09:31:58
双向链表中链接是双向的:一个链向下一个元素,另一个链向上一个元素,如下图所示:
双向链表结构代码如下:
class Node {
constructor(element) {
this.element = element;
this.prev = null;
this.next = null;
}
} class DoubledLinskLIst {
constructor() {
this.length = 0;
this.head = null;
this.tail = null;
} append(element) {
let node = new Node(element);
if (this.getHead() === null) { //空链表的情况
this.head = node;
this.tail = node; //如果是空链表,插入一个元素,它的head和tail都指向node
}
else {
let current = this.getTail();
current.next = node;
node.prev = current;
this.tail = node;
}
this.length++;
} insert(position, element) { if (position >= 0 && position <= this.size()) {
let current = this.getHead(),
previous,
index = 0,
node = new Node(element);
if (position === 0) {
if (!this.getHead()) { //空链表
this.head = node;
this.tail = node;
}
else {
this.head = node;
node.next = current;
current.prev = node;
} }
else if (position === this.size()) {
current = this.getTail();
this.tail = node;
node.prev = current;
current.next = node;
}
else { while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = node;
node.prev = previous;
node.next = current;
current.prev = node; }
this.length++;
return true;
}
else {
return false;
}
} removeAt(position) {
if (position >= 0 && position < this.size()) {
let current = this.getHead(), index = 0, previous;
if (position === 0) {
this.head = current.next;
if (this.size() === 1) { //链表只有一个数据
this.tail = null;
}
else {
current.next.prev = null;
} }
else if (position === this.size() - 1) {
current = this.getTail();
this.tail = current.prev;
current.prev.next = null;
}
else {
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
current.next.prev = previous; }
this.length--;
return current.element;
}
else {
return null;
}
} indexOf(element) {
let current = this.getHead(), index = 0;
while (current) {
if (current.element === element) {
return index;
}
index++;
current = current.next;
}
return -1;
} remove(element) {
let position = this.indexOf(element);
return this.removeAt(position);
} getHead() {
return this.head;
} getTail() {
return this.tail;
} size() {
return this.length;
} isEmpty() {
return this.length === 0;
} toString() { let current = this.getHead(),
string = ''; while (current) {
string += current.element + (current.next ? ', ' : '');
current = current.next;
}
return string; } print() {
console.log(this.toString());
}
}
参考:《JavaScript数据结构与算法--第二版》
最新文章
- jQuery实用小技巧--输入框文字获取和失去焦点
- c++共享内存(转载)
- PHP5.6.15连接Sql Server 2008配置方案
- React-Native 给客户端来个「同音词模糊搜索」
- [solr] - spell check
- Codeforces Round #140 (Div. 2)
- Redis性能测试工具benchmark简介
- easyui combo下拉框多选框
- canvas绘制文字
- ToString()字符转换类型
- Mediator 模式
- sql 判断表、列、视图等是否存在
- c++ build options(important)
- 【Unity与23种设计模式】责任链模式(Chain of Responsibility)
- 在pycharm中查看内建函数源码
- mybatis使用枚举优化
- Tomcat优化之容易集合经验
- C# struct and enum
- HTML转义字符 Unicode和CSS伪类介绍
- JS设置cookie、读取cookie、删除cookie(转载)