/**
* 链表的构造函数
*/
class LinkedList {
constructor() {
this.head = null;
}
}
/**
* 链表节点的构造函数
*/
class LinkedNode {
constructor(data, next = null) {
(this.data = data), (this.next = next);
}
}
/**
* 获取当前链表的长度
*/
LinkedList.prototype.length = function () {
let node = this.head;
let length = 0;
while (node) {
length++;
node = node.next
}
return length;
}
/**
* 根据下标获取当前链表节点
*
* @param index {Number} 必需
*
* @returns 返回查询到的节点,若未查询到返回null
*/
LinkedList.prototype.get = function (index) {
if (index < 0 || index > this.length()) {
throw new RangeError('下标参数越界');
}
let node = this.head;
let count = 0;
while (node) {
if (count === index) {
return node;
}
count++;
node = node.next;
}
return null;
}
/**
* 插入链表节点
*
* @param data {Object} 节点只 必需
* @param index {Number} 节点下标,默认值为0
*
* @returns 返回链表的头节点
*/
LinkedList.prototype.insert = function (data, index = 0) {
if (index < 0 || index > this.length()) {
throw new RangeError('下标参数越界');
}
let newNode = new LinkedNode(data);
if (index == 0) {
newNode.next = this.head;
this.head = newNode;
return this.head;
}
let preNode = this.get(index - 1);
newNode.next = preNode.next;
preNode.next = newNode;
return this.head;
}
/**
* 删除链接节点
*
* @param index {Number} 节点下标
*
* @returns 被删除的节点
*/
LinkedList.prototype.delete = function (index) {
if (index < 0 || index > this.length()) {
throw new RangeError('下标参数越界');
}
if (index == 0) {
let temp;
temp = this.head;
this.head = this.head.next;
return temp;
}
let cur = this.get(index);
let preNode = this.get(index - 1);
preNode.next = cur.next;
cur.next = null;
return cur;
}
/**
* 更新节点值
*
* @param newData {Object} 新节点值
* @param index {Number} 节点下标
*/
LinkedList.prototype.update = function (newData, index) {
if (index < 0 || index > this.length()) {
throw new RangeError('下标参数越界');
}
this.get(index).data = newData;
}
/**
* 链表反转
*
* @returns 返回链表头节点
*/
LinkedList.prototype.reserve = function () {
let p = this.head;
let q = p.next;
let r = q.next;
p.next = null;
while (q.next) {
q.next = p;
p = q;
q = r;
r = r.next;
}
q.next = p;
this.head = q;
}
/**
* 遍历链表
*/
LinkedList.prototype.forEach = function (fn) {
let node = this.head;
while (node) {
fn.call(this, node);
node = node.next;
}
}
B
/**
* 将链表转化为数值组
* 返回一个新的数组对象,原链表不会发生任何变化
*/
LinkedList.prototype.toArray = function () {
let array = [];
this.forEach((node) => { array.push(node) });
return array;
}
数据结构 链表
最新推荐文章于 2022-12-22 18:05:46 发布