链表javascript实现

41 阅读1分钟

在算法学习过程中,数据结构的学习理解是必不可少的。基于这些数据结构可以实现很多性能很多的算法。本文使用 JavaScript 简单实现了一个链表结构。包含基本的增删改查功能。

class Node {
	constructor (val) {
		this.next = null;
		this.val = val;
	}
}

/**
    查找节点
    插入节点
    搜索/遍历节点
    删除节点
    查找上一个节点
**/
class List {
	constructor () {
		this.head = null;
		this.len = 0;
	}

	add(val) {
		let n = new Node(val);
		if (this.head === null) {
			this.head = n;
		} else {
			let t = this.head;
			while (t.next) {
				t = t.next;
			}
			t.next = n;
		}
		this.len++;
		return this.head;
	}
	search (val) {
		if (this.head === null) {
			return null;
		}
		let t = this.head;
		while (t.next) {
			if (t.val === val) break;
			t = t.next;
		}
		return t;
	}
	insert(val, node) {
		if (!this.isNode(node)) {
			throw new Error("请输入正确的node");
		}
		let n = new Node(val);

		n.next = node.next;
		node.next = n;
		this.len++;
	}
	preNode(node) {
		if (this.head === null || this.head.val === node.val) return null;
		let t = this.head;
		let pre = t;
		while(t.next) {
			if (t.val === node.val) break;
			pre = t;
			t = t.next;
		}
		return pre;
	}
	delete(node) {
		if (!this.isNode(node)) {
			throw new Error("请输入正确的node");
		}
		let preNode = this.preNode(node);
		preNode.next = node.next;
		this.len--;
	}
	traverse() {
		let p = this.head;
		while(p) {
			console.log(p.val);
			p = p.next;
		}
	}
	length() {
		return this.len;
	}
	isNode(node) {
		return node instanceof Node;
	}

	reverse() {
		if (this.head === null || this.head.next === null) return;
		let pre = this.head;
		let current = this.head.next;
		let next = this.head.next.next;
		pre.next = null;
		while (current) {
			current.next = pre;
			pre = current;
			current = next;
			next = next&&next.next || null;
		}
		this.head = pre;
	}
}