Leetcode 203.删除了LinkedList元素



我总是很难理解虚拟/当前指针如何更新头指针

下面的代码是问题语句的解决方案给定一个链表的头和一个整数val,删除链表中所有有Node的节点。val == val,并返回新的头部

public ListNode removeElements(ListNode head, int val) {
ListNode curr = head;
while(curr != null && curr.val == val){
curr = curr.next;
}

while(curr != null && curr.next != null){
if(curr.next.val == val){
curr.next = curr.next.next;
}
curr = curr.next;
}
return head;
}

下面的代码在head = [7,7,7,7], val = 7的情况下失败期望答案:[],上述代码的答案:[7,7,7,7]

测试用例只进入第一个while循环,其中curr被更新为下一个指针。我期望head也被更新(head在其他测试用例中执行第二个while循环时得到更新)。对此的任何解释都会很有帮助

您的代码从未更新head,但如果第一个节点具有要删除的值,则head将需要更改…对于您提供的示例列表,该函数甚至应该返回null。

代码中的第一个循环应该更新head,而不是currcurr只在第二个循环中开始发挥作用:

public ListNode removeElements(ListNode head, int val) {
while(head != null && head.val == val){
head = head.next;
}

ListNode curr = head;
while(curr != null && curr.next != null){
if(curr.next.val == val){
curr.next = curr.next.next;
}
curr = curr.next;
}
return head;
}

最新更新