Skip to content

2487. Remove Nodes From Linked List 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  ListNode* removeNodes(ListNode* head) {
    if (head == nullptr)
      return nullptr;
    head->next = removeNodes(head->next);
    return head->next != nullptr && head->val < head->next->val ? head->next
                                                                : head;
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public ListNode removeNodes(ListNode head) {
    if (head == null)
      return null;
    head.next = removeNodes(head.next);
    return head.next != null && head.val < head.next.val ? head.next : head;
  }
}
1
2
3
4
5
6
class Solution:
  def removeNodes(self, head: ListNode | None) -> ListNode | None:
    if not head:
      return None
    head.next = self.removeNodes(head.next)
    return head.next if head.next and head.val < head.next.val else head