js实现链表

2021-04-10 12:29

阅读:620

标签: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++ 

  

js实现链表

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

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


评论


亲,登录后才可以留言!