代码之家  ›  专栏  ›  技术社区  ›  fighg

如何获得链表的下一个值?

  •  0
  • fighg  · 技术社区  · 6 年前

    我正在尝试用javascript编写一个链接列表。我有一个类、一个构造函数和一个addtoLast函数,它提供了彼此之间的连接。

    但在addtoLast函数中,我无法访问“ 下一个 “我的任何对象的属性。

    上面写着

    无法在编号“x”上创建属性“next”

    (x作为第一个值和链表的标题)

    代码为:

    class LinkedList
    {
        constructor()
        {
            this.head=[];
            this.next=null;
            this.length=0;
        }
    
        addtoLast(value)
        {
            if(this.head==null)
            {
                this.head=value;
                this.length++;
            }
            else
            {
                let now=this.head;
                let newNode=value;
    
                while(now.next!=null)
                now=now.next;
    
                now.next=newNode;   //it gives that error
                newNode.next=null;  //and it gives too!
                this.length++;
            }  
        }
    }
    
    //and my main function is:
    
    let example = new LinkedList();
    example.head = 3;
    example.addtoLast(9);
    document.write(example);

    如有任何评论,我将不胜感激:)

    1 回复  |  直到 6 年前
        1
  •  0
  •   Sphinx    6 年前

    我修复了以下问题:

    1. this.head :它不应该是一个数组(否则列表有多个标头),它应该是一个对象,并且应该用null或 {value:'',next:null}

    2. let newNode={'value':value, 'next':null}; 遵循与相同的规则 这头

    3. 改变 example.head = 3; example.head = {'value':3, 'next':null}; 附言 :但这将导致列表的长度错误。

    4. 已删除 this.next=null ,接下来应该是每个节点的一个属性。 下面是一个工作示例。

    class LinkedList
    {
        constructor()
        {
            this.head=null;
            //this.next=null;
            this.length=0;
        }
    
        addtoLast(value)
        {
            if(!this.head)
            {
                this.head={'value':value, 'next':null};
                this.length++;
            }
            else
            {
                let now=this.head;
                let newNode={'value':value, 'next':null};
    
                while(now.next!=null)
                now=now.next;
    
                now.next=newNode;   //it gives that error
                newNode.next=null;  //and it gives too!
                this.length++;
            }  
        }
    }
    
    //and my main function is:
    
    let example = new LinkedList();
    //example.head = {'value':3, 'next':null};
    example.addtoLast(3);
    example.addtoLast(9);
    example.addtoLast(10);
    console.log(example);
    document.write(example);