LeetCode - Algorithms - 203. Remove Linked List Elements

Problem

203. Remove Linked List Elements

Java

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
/**
* 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; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null)
return head;
ListNode previousNode = head;
if (head != null) {
ListNode node = head.next;
while (node != null) {
if (node.val == val) {
ListNode obsoleteNode = node;
previousNode.next = node.next;
obsoleteNode = null;
}
else
previousNode = node;
node = node.next;
}
}
if (head.val == val) {
ListNode obsoleteNode = head;
head = head.next;
obsoleteNode = null;
}
return head;
}
}

Submission Detail

  • 65 / 65 test cases passed.
  • Runtime: 1 ms, faster than 82.56% of Java online submissions for Remove Linked List Elements.
  • Memory Usage: 40 MB, less than 10.13% of Java online submissions for Remove Linked List Elements.