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
删除链表中所有值为val的节点。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode removeElements(ListNode head, int val) { ListNode node = head; while (node != null && node.val == val){ node = node.next; } head = node; while (node != null && node.next != null){ if (node.next.val == val){ ListNode delete = node.next; while (delete != null && delete.val == val){ delete = delete.next; } node.next = delete; } node = node.next; } return head; } }
当然代码可以接着优化。但是想法没什么区别。