|
| 1 | +packageeasy; |
| 2 | + |
| 3 | +importclasses.ListNode; |
| 4 | +importutils.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 | +publicclassRemoveLinkedListElements { |
| 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 | +publicListNoderemoveElements(ListNodehead,intval) { |
| 24 | +ListNodedummy =newListNode(-1); |
| 25 | +dummy.next =head; |
| 26 | +ListNodecurr =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 | +returndummy.next; |
| 36 | +} |
| 37 | + |
| 38 | +publicstaticvoidmain(String...strings){ |
| 39 | +RemoveLinkedListElementstest =newRemoveLinkedListElements(); |
| 40 | +intval =1; |
| 41 | +ListNodehead =newListNode(1); |
| 42 | +ListNoderes =test.removeElements(head,val); |
| 43 | +CommonUtils.printList(res); |
| 44 | +} |
| 45 | +} |