@@ -19,7 +19,12 @@ public class RemoveLinkedListElements {
19
19
* 1. Eventually, we should return dummy.next as the final result.
20
20
* 2. we assign head to curr, dummy to prev
21
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*/
22
+ * 4. each time, we only move one node forward, so we don't need another while loop inside the while loop
23
+ * 5. KEY: if(curr.val == val), then curr is the node we want to remove, so, we'll assign curr.next to prev.next, thus, prev won't have that node
24
+ * else, we'll keep moving prev forward, so, just do prev = prev.next
25
+ * but, for both cases, we'll also move curr forward, so we put curr = curr.next in the outside.
26
+ *
27
+ * */
23
28
public ListNode removeElements (ListNode head , int val ) {
24
29
ListNode dummy = new ListNode (-1 );
25
30
dummy .next = head ;
@@ -37,8 +42,14 @@ public ListNode removeElements(ListNode head, int val) {
37
42
38
43
public static void main (String ...strings ){
39
44
RemoveLinkedListElements test = new RemoveLinkedListElements ();
40
- int val = 1 ;
45
+ int val = 6 ;
41
46
ListNode head = new ListNode (1 );
47
+ head .next = new ListNode (2 );
48
+ head .next .next = new ListNode (6 );
49
+ head .next .next .next = new ListNode (3 );
50
+ head .next .next .next .next = new ListNode (4 );
51
+ head .next .next .next .next .next = new ListNode (5 );
52
+ head .next .next .next .next .next .next = new ListNode (6 );
42
53
ListNode res = test .removeElements (head , val );
43
54
CommonUtils .printList (res );
44
55
}
0 commit comments