Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 --> 4 --> 5
set Dummy node
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode removeElements(ListNode head, int val) { 11 ListNode dummy = new ListNode(-1); 12 dummy.next = head; 13 ListNode cur = dummy; 14 while (cur.next != null) { 15 if (cur.next.val == val) { 16 cur.next = cur.next.next; 17 } 18 else cur = cur.next; 19 } 20 return dummy.next; 21 } 22 }
这题有个重要的follow up,就是在一个环里怎么删除节点: