Remove all elements from a linked list of integers that have value val.
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)。(头节点指向链表的第一个节点)
加入头节点有两个作用:
注意:
line 10 一定要加else,否则可能抛出NullPointerException异常。比如 Input: head = 1->2->3->3->4->5->3->null, val = 3。
if语句要用准!
代码:
1 public ListNode removeElements(ListNode head, int val) { 2 ListNode dummy = new ListNode(0); 3 dummy.next = head; 4 head = dummy; 5 6 while (head.next != null){ 7 if (head.next.val == val) { 8 head.next = head.next.next; 9 } 10 else head = head.next; 11 } 12 return dummy.next; 13 }
Lintcode452-Remove Linked List Elements-Easy
原文:https://www.cnblogs.com/Jessiezyr/p/10648005.html