码迷,mamicode.com
首页 > Web开发 > 详细

js实现链表

时间:2020-03-06 17:07:05      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:current   append   position   ++   let   end   app   class   insert   

    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实现链表

标签:current   append   position   ++   let   end   app   class   insert   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!