【发布时间】:2020-03-24 03:15:22
【问题描述】:
如何删除 从具有值 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 []
请建议如何实现。我将当前节点存储在前一个节点中
【问题讨论】:
-
如果匹配元素在
head中,该功能将不起作用,因为您一直返回head。 -
您需要将其作为特殊情况处理。
-
怎么处理??
-
if (head.val == val) { ... } -
好的,试试这样
while (head!=null){ if(head.val == val){ head = head.next; }else { break; } }
标签: javascript algorithm data-structures linked-list