【问题标题】:how I can reach the next value of a linked list?我怎样才能达到链表的下一个值?
【发布时间】:2018-03-09 22:55:11
【问题描述】:

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

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

上面写着

无法在数字“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);

我会感谢任何评论:)

【问题讨论】:

  • let newNode=value; 这应该怎么做?而且您似乎不了解链表
  • now is an integer,您不能将 next 属性分配给整数,如错误所示。相反,将整数包装在节点对象{ value: now, next: ... }
  • 你声明了this.head=[],你的列表有多个头?
  • newNode 只是值的变量。我们用它来达到下一个值。所以我们不能说value.next 这就是我的意思。 @JonasW。
  • 你建议我做那个构造函数必须有“节点部分”@caesay

标签: javascript oop properties linked-list null


【解决方案1】:

我修复了以下问题:

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

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

  3. example.head = 3; 更改为example.head = {'value':3, 'next':null}; PS:但是会导致列表长度不对。

  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);

【讨论】:

  • 那么因为let newNode={'value':value, 'next':null}; 这行newNode.next=null; 是不必要的。非常感谢@Sphinx
猜你喜欢
  • 2013-06-29
  • 2020-07-24
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多