首页 > Web开发 > 详细

js实现链表

时间:2020-03-06 17:02:23      阅读:54      评论:0      收藏:0      [点我收藏+]
    class Node {
      constructor(elem) {
        this.elem = elem;
        this.next = null;
      }
    }
    class LinkedList {
      constructor() {
        this.head = null;
        this.length = 0;
      }
      // 末尾加入
      append(element) {
        let node = new Node(element);
        if (this.head) {
          let current = this.head;
          while (current.next) {
            current = current.next;
          }
          current.next = node;
        } else {
          this.head = node;
        }
        this.length++;
      }
      // 插入 未考虑position超出长度
      insert(position, element) {
        let node = new Node(element);
        let index = 0;
        let current = this.head;
        let previous = null;
        if (position === 0) {
          if (this.head) {
            this.head = node;
            node.next = current;
          } else {
            this.head = node;
          }
        } else {
          while (index++ < position) {
            previous = current;
            current = current.next;
          }
          previous.next = node;
          node.next = current;
        }
        this.length++;
      }
      // 移除
      remove(position) {
        let current = this.head;
        if (position === 0) {
          if (this.head) {
          } else {
          }
        }
      }
    }

  

js实现链表

原文:https://www.cnblogs.com/Mijiujs/p/12427372.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!