Leetcode 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
Analysis
To solve this problem, we keep two pointers pre and cur when scanning the LinkedList. Once the current node’s value equals to the target value, we remove the cur node by set pre.next = cur.next;
To make the implementation easier, we can use a dummy variable point to the head of the list. And initialize pre = dummy and cur = head. Note that this idea can also be applied to solve the problem: remove Nth node from the end of LinkedList.
Java Implementation
|
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 dummy = new ListNode(-1); dummy.next = head; ListNode pre = dummy; ListNode cur = head; while(cur != null) { if(cur.val == val) { pre.next = cur.next; cur = cur.next; } else { pre = cur; cur = cur.next; } } return dummy.next; } } |
Reference
https://leetcode.com/problems/remove-linked-list-elements/











