用Javascript实现链表

github主页:https://github.com/A15162252289

什么是链表

链表存储有序的元素集合,但不同于数组,链表中的元素在内存中不是连续放置的。每个元素由一个存储元素本身的节点和指向下一个元素的引用组成。

下图为单向链表的示意图
链表
相对于传统数组链表的好处在于,添加和删除元素的时候不需要移动其他元素。然而,链表需要使用指针,因此实现链表时应该额外注意。数组的另一个细节是可以直接访问任何位置的元素,而想要访问链表中间的一个元素,需要从起点(表头)开始迭代列表直到找到所需元素。

如何实现单向链表

function LinkedList () {
    let Node = function (element) {
        this.element = element;
        this.next = null;
    }; //定义链表中单个节点
    let length = 0; //定义链表长度
    let head = null; //定义链表第一项
    this.append = function (element) {
        let node = new Node(element);
        let curNode;
        if (head == null) {
            head = node;
        } else {
            curNode = head;
            while (curNode.next) {
                curNode = curNode.next;
            }
            curNode.next = node;
        }
        length++;
    }; //向链表末尾添加一项
    this.removeAt = function (position) {
        //检查越界值
        if (position > -1 && position < length) {
            let curNode = head;
            let preNode;
            let index = 0;
            if (position === 0) {
                head = curNode.next;
            } else {
                while (index++ < position) {
                    preNode = curNode;
                    curNode = curNode.next;
                }
                preNode.next = curNode.next;
            }
            length--;
            return curNode.element;
        }
    }; //删除特定位置的某项
    this.insert = function (position, element) {
        let node = new Node(element);
        let curNode = head;
        let preNode;
        let index = 0;
        if (position >= 0 && position <= length) {
            if (position === 0) {
                head = node;
                node.next = curNode;
            } else {
                while (index++ < position) {
                    preNode = curNode;
                    curNode = curNode.next;
                }
                preNode.next = node;
                node.next = curNode;
            }
            length++;
            return true;
        } else {
            return false;
        }
    }; //将元素添加到指定位置
    //其他方法
}

这里实现了最重要的几种方法,其他的不做赘述;

猜你喜欢

转载自blog.csdn.net/qq_39833020/article/details/83179433