|
| 1 | +package easy; |
| 2 | + |
| 3 | +import classes.ListNode; |
| 4 | +import utils.CommonUtils; |
| 5 | + |
| 6 | +/**203. Remove Linked List Elements QuestionEditorial Solution My Submissions |
| 7 | +Total Accepted: 74027 |
| 8 | +Total Submissions: 249238 |
| 9 | +Difficulty: Easy |
| 10 | +Remove all elements from a linked list of integers that have value val. |
| 11 | +
|
| 12 | +Example |
| 13 | +Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 |
| 14 | +Return: 1 --> 2 --> 3 --> 4 --> 5*/ |
| 15 | +public class RemoveLinkedListElements { |
| 16 | + /**This is a very good question to test your understanding of pointers/memory/addresses, although it's marked as EASY. |
| 17 | + * All the three nodes: dummy, curr and prev are indispensable. |
| 18 | +
|
| 19 | + * 1. Eventually, we should return dummy.next as the final result. |
| 20 | + * 2. we assign head to curr, dummy to prev |
| 21 | + * 3. and then we use prev and curr to traverse through the list and do the work |
| 22 | + * 4. each time, we only move one node forward, so we don't need another while loop inside the while loop*/ |
| 23 | + public ListNode removeElements(ListNode head, int val) { |
| 24 | + ListNode dummy = new ListNode(-1); |
| 25 | + dummy.next = head; |
| 26 | + ListNode curr = head, prev = dummy; |
| 27 | + while(curr != null){ |
| 28 | + if(curr.val == val){ |
| 29 | + prev.next = curr.next; |
| 30 | + } else { |
| 31 | + prev = prev.next; |
| 32 | + } |
| 33 | + curr = curr.next; |
| 34 | + } |
| 35 | + return dummy.next; |
| 36 | + } |
| 37 | + |
| 38 | + public static void main(String...strings){ |
| 39 | + RemoveLinkedListElements test = new RemoveLinkedListElements(); |
| 40 | + int val = 1; |
| 41 | + ListNode head = new ListNode(1); |
| 42 | + ListNode res = test.removeElements(head, val); |
| 43 | + CommonUtils.printList(res); |
| 44 | + } |
| 45 | +} |
0 commit comments