如何在javascript中从列表中删除所有项目



如何删除从值为val的整数链表中删除所有元素。

示例

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

我试过像这个

var removeElements = function (head, val) {
if (!head) return null;
let curr = head,
pre = curr;
while (curr != null) {
if (curr.val == val) {
pre.next = curr.next
curr = curr.next;
} else {
pre = curr;
curr = curr.next;
}
}
return head
};

我的第一个测试用例运行良好

console.log(JSON.stringify(removeElements(
{
"val": 1,
"next": {
"val": 2,
"next": {
"val": 6,
"next":
{
"val": 3,
"next":
{
"val": 4,
"next":
{
"val": 5, "next":
{"val": 6, "next": null}
}
}
}
}
}
}
, 6)));
// working fine
// expected  1->2->3->4->5 or [1,2,3,4,5]

但它在低于的情况下失败

console.log(JSON.stringify(removeElements(
{
"val": 1,
"next": {
"val": 1,
"next": null
}
}, 1)));
// getting {"val":1,"next":null} or [1]
// expected null or []

请建议如何实现这一点。我正在将当前节点存储在上一个节点中

对于特殊情况,我像这样检查

var removeElements = function (head, val) {
if (!head) return null;
while (head!=null){
if(head.val == val){
head = head.next;
}else {
break;
}
}
let curr = head,
pre = curr;
while (curr != null) {
if (curr.val == val) {
pre.next = curr.next
curr = curr.next;
} else {
pre = curr;
curr = curr.next;
}
}
return head
};

如果我不理解这个问题,我很抱歉,这就是你想要的吗?

var removeElements = function (head, val) {
if (!head) return null;
let curr = head;
let pre = null;
while (curr != null) {
if (curr.val == val) {
if (pre) {
pre.next = curr.next;
} else {
head = curr.next;
}
} else {
pre = curr;
}
curr = curr.next;
}
return head;
};

相关内容

  • 没有找到相关文章

最新更新