js实现对链表的操作

关于对链表这种数据结构,原来在c语言中有提到过,链表一种长度可变的动态列表。分为单向列表和双向列表。

  • 单向列表:每个节点不仅存在自身的值,同时也存在指向下一个元素的指针
  • 双向链表:它的节点中存在两个指针,一个指向上一个节点的指针,一个指向下一个节点的指针,并且存在自己的一个值。
// 定义一个几点类型构造函数
function Node(v) {
    this.val = v;
    this.next = null;
}
function ArrayList() {
    // 定义链表的头结点
    this.head = new Node(null);
    // 定义一个节点,它始终指向链表中的最后一个节点
    this.tail = this.head;
    // 在链表的末尾添加一个节点
    this.append = function (v) {
        let node = new Node(v);
        this.tail.next = node;
        // 用this.tail始终指向当前链表的最后一个节点
        this.tail = node;
    };
    // 在第no个节点后面添加一个新节点
    this.insertAt = function (no, v) {
        let node = new Node(v);
        let tempNode = this.head;
        for (let i = 0; i < no; i++) {
            if (tempNode.next) {
                tempNode = tempNode.next;
            } else {
                break;
            }
        }
        node.next = tempNode.next;
        tempNode.next = node;
    };
    // no表示要删除节点的前一个节点序号
    this.removeAt = function (no) {
        let tempNode = this.head;
        for (let i = 0; i < no; i++) {
            if (tempNode.next) {
                tempNode = tempNode.next;
            } else {
                break;
            }
        }
        // 获取需要删除的节点node2
        let node2 = tempNode.next;
        if (node2) {
            // 删除节点
            tempNode.next = node2.next;
            if (node2.next == null) {
                // 如果删除的节点的next是null则表示查找到的被删除节点的上一个节点就是尾结点
                this.tail = tempNode;
            }
        }
    };
}
function Iterator(arrayList) {
    // 获取链表的头结点
    this.point = arrayList.head;
    // 判断当前节点是否存在下一个节点,如果存在将当前节点指向下一个节点并返回true,反之返回false
    this.hasNext = function () {
        if (this.point.next) {
            this.point = this.point.next;
            return true;
        } else {
            return false;
        }
    };
    // 获取下一个节点的值
    this.next = function () {
        return this.point.val;
    }
}
var arry = new ArrayList();
arry.append(1);
arry.append(2);
arry.append(3);
arry.insertAt(1, 8);
arry.insertAt(0, 9);
arry.insertAt(100, 100);
arry.insertAt(1000, 1000);
arry.insertAt(1, 200);
arry.insertAt(200, 2000);
iterator = new Iterator(arry);
while (iterator.hasNext()) {
    document.write(iterator.next());
    document.write('<br/>');
}
发布了19 篇原创文章 · 获赞 3 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/u010510187/article/details/103075125
今日推荐