Home [Easy] Remove Linked List Elements
Post
Cancel

[Easy] Remove Linked List Elements

‘Remove Linked List Elements’ in LeetCode (Easy)


📌 Problem

https://leetcode.com/problems/remove-linked-list-elements/

📌 Answer

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
        while (head != null && head.val == val) head = head.next;
        ListNode curr = head;
        while (curr != null && curr.next != null) {
            // System.out.println("curr before : " + curr.val);
            if (curr.next.val == val) curr.next = curr.next.next; // remove next
            else curr = curr.next; // go next
            // System.out.println("curr after : " + curr.val);
            // System.out.println();
        }
        return head;
    }
}

/**
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]

Stdout
curr before : 1
curr after : 2

curr before : 2
curr after : 2

curr before : 2
curr after : 3

curr before : 3
curr after : 4

curr before : 4
curr after : 5

curr before : 5
curr after : 5
**/
1
2
3
4
5
6
7
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) return null;
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }
}
This post is licensed under CC BY 4.0 by the author.

[Easy] Reverse Linked List

[Easy] Intersection of Two Linked Lists

Comments powered by Disqus.