Javascript 中的链表(Deletehead)[关闭]

问题描述 投票:0回答:1

1 .如果链表不为空,则将当前头移动到下一个节点 2.如果链表为空,则不执行任何操作 下面的代码是否正确?如果错了请告诉我答案。

下面的代码是否正确?如果错了请告诉我答案。

deleteHead(){
    if(!this.head ==  null){
        this.head = tail.next;
    }else{
        return;
    }
    return null;
}
javascript singly-linked-list
1个回答
2
投票

我不明白为什么这个条件

(!this.head ==  null)
必须写得这么复杂。

如果链表不为空,则表示

head!=null
true
,需要将
head
向前移动一个节点。这是由
this.head = this.head.next
而不是
tail.next
完成的。尾指针位于链表的结束节点。

所以整体简化后的功能就变成了

deleteHead(){
    if(this.head==null){
        return;
    }
    this.head = this.head.next;
}

deleteHead(){
    if(!this.head){
        return;
    }
    this.head = this.head.next;
}
© www.soinside.com 2019 - 2024. All rights reserved.