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
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
Solution: Special attention when head changes and maintaining tail.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | /** * 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 p = head; while (p != null && p.val == val) { p = p.next; } head = p; ListNode tail = head; while (p != null) { if (p.val == val) { tail.next = p.next; } else { tail = p; } p = p.next; } return head; } } |
No comments:
Post a Comment