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
正确代码:
1 /** 2 * Definition for ListNode 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 13 public class Solution { 14 /** 15 * @param head: a ListNode 16 * @param val: An integer 17 * @return: a ListNode 18 */ 19 public ListNode removeElements(ListNode head, int val) { 20 ListNode dummy = new ListNode(0); 21 dummy.next = head; 22 head = dummy; 23 while (head.next != null) { 24 if (head.next.val == val) { 25 head.next = head.next.next; 26 } else { 27 head = head.next; 28 } 29 } 30 return dummy.next; 31 } 32 }