Remove Linked List Elements
iven 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.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1
Output: []
Example 3:
Input: head = [7,7,7,7], val = 7
Output: []
Constraints:
The number of nodes in the list is in the range [0, 10^4].
We'll use a dummy node to handle edge cases like removing the head.
Steps:
-
Create a dummy node (
dummy
) before the head. -
Use a
current
pointer starting fromdummy
. -
Loop while
current.next
is not null:-
If
current.next.val == val
, skip it usingcurrent.next = current.next.next
-
Else, move forward.
-
-
Return
dummy.next
(new head).
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class Solution {
public ListNode removeElements(ListNode head, int val) {
// Step 1: Create a dummy node
ListNode dummy = new ListNode(-1);
dummy.next = head;
// Step 2: Initialize current pointer
ListNode current = dummy;
// Step 3: Traverse and remove matching nodes
while (current.next != null) {
if (current.next.val == val) {
current.next = current.next.next; // skip node
} else {
current = current.next; // move ahead
}
}
// Step 4: Return new head
return dummy.next;
}
}
Comments
Post a Comment