Skip to content

Commit 0f351ba

Browse files
some extra notes on remove linked list elements
1 parent c44cb4d commit 0f351ba

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

EASY/src/easy/RemoveLinkedListElements.java

+13-2
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,12 @@ public class RemoveLinkedListElements {
1919
* 1. Eventually, we should return dummy.next as the final result.
2020
* 2. we assign head to curr, dummy to prev
2121
* 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+
* */
2328
public ListNode removeElements(ListNode head, int val) {
2429
ListNode dummy = new ListNode(-1);
2530
dummy.next = head;
@@ -37,8 +42,14 @@ public ListNode removeElements(ListNode head, int val) {
3742

3843
public static void main(String...strings){
3944
RemoveLinkedListElements test = new RemoveLinkedListElements();
40-
int val = 1;
45+
int val = 6;
4146
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);
4253
ListNode res = test.removeElements(head, val);
4354
CommonUtils.printList(res);
4455
}

0 commit comments

Comments
 (0)