js实现链表

时间:2020-03-06 17:07:05   收藏:0   阅读:53
    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 {
          }
        }
      }
    }

  

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!