
Remove Linked List Elements
Remove all elements from a linked list of integers that have value val
.
Example
Example 1:
Input: head = 1->2->3->3->4->5->3->null, val = 3
Output: 1->2->4->5->null
Example 2:
Input: head = 1->1->null, val = 1
Output: null
思路:
函数参数中的ListNode head是链表中的第一个节点。所以要先加入头节点dummy, 并使head变为头节点(line 4)。(头节点指向链表的第一个节点)
加入头节点有两个作用:
- dummy node 始终指向链表的第一个节点,这样返回整个链表只需要dummy.next
- head 作为头节点,使对链表第一个节点的操作(插入,删除等)和链表内其他节点相同,不用单独考虑第一个节点操作的特殊性。
错误示范:
while (head.next != null) {
if (head.next.val == val) {
head.next = head.next.next;
}
head = head.next;
}
可能抛出NullPointerException异常。比如
Input: head = 1->2->3->3->4->5->3->null, val = 3。
原因:
这个题是一个if-else case: 要么head结点的下一个结点值等于要删除的值,要么不等于。
如果是第一种情况,那么在改变head.next属性后,head节点不需要向下移动一个。因为此时head.next 属性已经改变,需要重新判断 head.next != null 和 head.next.val ?= val
正确代码:
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/ public class Solution {
/**
* @param head: a ListNode
* @param val: An integer
* @return: a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
while (head.next != null) {
if (head.next.val == val) {
head.next = head.next.next;
} else {
head = head.next;
}
}
return dummy.next;
}
}