用js实现数据结构(一)---线性表

184 阅读1分钟

线性表

包括有顺序存储结构和链式存储结构

一、顺序存储结构

顺序存储结构线性表,即数组,在原生js中已经包含该种数据结构,所以在这里不做过多讲述。

这种数据结构可以通过索引直接定位,便于查找,但是不利于做删除、插入操作。

二、链式存储结构

链式存储结构线性表,即链表。

这种数据结构无法通过索引直接定位,只能从头按顺序查找下去。但是便于做删除和插入操作。

下面,我们用js实现他。

        class Node {
            constructor(value) {
                this.value = value;
                this.next = null;
            }
        }
        class Linklist {
            constructor(){
                this.head = new Node(null, null);
                this.length = 0;
            }
            // 将节点node插入到第n个位置
            insertNode(node ,n) {
                let target = this.head;
                for(let i=1; i<n && target.next !== null ;i++) {
                    target = target.next;
                }
                node.next = target.next;
                target.next = node;
                this.length++;
                return this.head;
            }
            // 删除指定位置的节点
            deleteNode(n) {
                let target = this.head;
                for(let i=1; i<n && target.next !== null; i++) {
                    target = target.next;
                }
                let delNode = target.next;
                if(delNode !== null) {
                    target.next = target.next.next;
                    this.length--;
                }
                return delNode;
            }
            // 获取指定的节点
            getNode(n) {
                let target = this.head.next;
                for(let i=1; i<n && target !== null; i++){
                    target = target.next;
                }
                return target;
            }
            // 遍历链表
            forEach(cb){
                let target = this.head.next;
                while(target !== null){
                    cb(target);
                    target = target.next;
                }
            }
        }
        let l = new Linklist();
        let n1 = new Node(1);
        let n2 = new Node(2);
        let n3 = new Node(3);
        let n4 = new Node(4);
        l.insertNode(n1,1);
        l.insertNode(n2,2);
        l.insertNode(n3,2);
        l.insertNode(n4,5);
        l.forEach(node => console.log(node.value)); // 1 3 2 4
        console.log(l.deleteNode(5)?.value ?? null); // null
        console.log(l.deleteNode(3).value);// 2
        console.log(l.deleteNode(3).value);// 4
        l.forEach(node => console.log(node.value));// 1 3
        console.log(l.length);// 2
        console.log(l.getNode(2));// 3
        console.log(l.getNode(3));// null