【问题标题】:Linked List issue when inserting a new item in Javascript在 Javascript 中插入新项目时出现链表问题
【发布时间】:2022-12-05 07:27:37
【问题描述】:

我有链表的下一个实现:

class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

class LinkedLIst {
  constructor() {
    this.head = {};
  }

  add(head) {    
    if(!this.head.next) {
      this.head = new Node(head);
    }

    this.head.next = new Node(head);
  }
}


const list = new LinkedLIst();
list.add(1)
list.add(2)
list.add(3)


console.log(list)

我不明白,为什么列表中没有添加2?以及如何解决这个问题?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    由于这是一个链表,我假设你想在最后插入。为此,您可以创建一个tail 属性。

    然后,在您的add 方法中,您可以检查是否不存在任何元素,然后将headtail 设置为新节点。如果至少有1个元素,你可以在新节点旁边设置tail,最后,让tail指向新节点。

    class Node {
      constructor(data) {
        this.data = data;
        this.next = null;
      }
    }
    
    class LinkedLIst {
      constructor() {
        this.head = null;
        this.tail = null;
      }
    
      add(value) {    
        const newNode = new Node(value)
        if (this.head === null) {
          this.head = this.tail = newNode
        } else {
          this.tail.next = newNode
          this.tail = newNode;
        }
      }
    }
    
    
    const list = new LinkedLIst();
    list.add(1)
    list.add(2)
    list.add(3)
    
    
    console.log(list)

    【讨论】:

      【解决方案2】:

      如果你不想使用 tail 只是迭代到链接列表的末尾

      class Node {
        constructor(data) {
          this.data = data;
          this.next = null;
        }
      }
      
      class LinkedLIst {
        constructor() {
          this.head = null;
        }
      
        add(head) {    
          
          if(!this.head) {
            this.head = new Node(head);
          }else{
            let ptr = this.head;    
            while(ptr.next!==null){
              ptr = ptr.next;
            }
            ptr.next=new Node(head);
          }
          
          
        }
      }
      
      
      const list = new LinkedLIst();
      list.add(1)
      list.add(2)
      list.add(3)
      
      
      console.log(list)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 2018-01-12
        • 1970-01-01
        • 1970-01-01
        • 2016-08-31
        • 1970-01-01
        • 2020-05-29
        相关资源
        最近更新 更多