Home Leetcode 2487 - Remove Nodes from Linked List
Post
Cancel

Leetcode 2487 - Remove Nodes from Linked List

Link to problem

Description

You are given the head of a linked list.

Remove every node which has a node with a greater value anywhere to the right side of it.

Return the head of the modified linked list.

Solution

Since every node needs to have a node with a greater value anywhere to the right side of it, the output linked list must be a decreasing sequence.

Therefore, to solve this problem, we will need to reverse the linked list using a stack and form the new list by checking the values when popping out the nodes.

Implementation

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
37
38
39
40
41
42
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:

    ListNode* removeNodes(ListNode* head) {
        stack<ListNode*> nodes;
        ListNode* cur = head;
        ListNode* newHead = nullptr;

        while (cur) {
            nodes.push(cur);
            cur = cur->next;
        }

        int max = 0;

        while (!nodes.empty()) {
            ListNode* node = nodes.top();
            nodes.pop();

            if (node->val >= max) {
                max = node->val;
                node->next = newHead;
                newHead = node;
            }
            else {
                delete node;
            }
        }

        return newHead;
    }
};
This post is licensed under CC BY 4.0 by the author.