- Remove Linked List Elements
Remove Linked List Elements
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
Solution:
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. if (head == null)
12. return null;
13. 14. ListNode f = new ListNode(0);
15. ListNode p = f;
16. 17. while (head != null) {
18. if (head.val != val) {
19. p.next = head;
20. p = p.next;
21. }
22. head = head.next;
23. }
24. 25. p.next = null;
26. 27. return f.next;
28. }
29. }
