LeetCode 2487: Remove Nodes From Linked List Solution
Master LeetCode problem 2487 (Remove Nodes From Linked List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2487. Remove Nodes From Linked List
Problem Explanation
Explanation
To solve this problem, we can iterate through the linked list in reverse order while keeping track of the maximum value encountered so far. If we find a node with a value greater than the current maximum, we remove that node from the list. Finally, we reverse the modified linked list to get the correct order.
- Start by iterating through the linked list in reverse order.
- Keep track of the maximum value encountered so far.
- If a node's value is greater than the current maximum, remove that node.
- Reverse the modified linked list to get the final result.
Time Complexity: O(N) where N is the number of nodes in the linked list. Space Complexity: O(1)
Solution Code
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public ListNode removeNodesFromList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode current = head;
ListNode prev = dummy;
int max = Integer.MIN_VALUE;
while (current != null) {
if (current.val > max) {
max = current.val;
prev = current;
} else {
prev.next = current.next;
}
current = current.next;
}
return reverseList(dummy.next);
}
private ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2487 (Remove Nodes From Linked List)?
This page provides optimized solutions for LeetCode problem 2487 (Remove Nodes From Linked List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2487 (Remove Nodes From Linked List)?
The time complexity for LeetCode 2487 (Remove Nodes From Linked List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2487 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2487 in Java, C++, or Python.