MrainW's Home

All things come to those who wait!

0%

LeetCode 203. Remove Linked List Elements

Question

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

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

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while(cur.next != null){
if(cur.next.val == val) cur.next = cur.next.next;
else cur = cur.next;
}
return dummy.next;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(1)

Welcome to my other publishing channels