The Indian Engineer

Problem 2487 Remove Nodes From Linked List

Posted on 3 mins

Monotonic-Stack Linked-List Pointers Stack Cpp

Problem Statement

Link - Problem 2487

Question

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.

Example 1

Input: head = [5,2,13,3,8]
Output: [13,8]
Explanation: The nodes that should be removed are 5, 2 and 3.
- Node 13 is to the right of node 5.
- Node 13 is to the right of node 2.
- Node 8 is to the right of node 3.

Example 2

Input: head = [1,1,1,1]
Output: [1,1,1,1]
Explanation: Every node has value 1, so no nodes are removed.

Constraints

Solution

/**
 * 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) {
        std::ios::sync_with_stdio(false);
        stack<ListNode*> st;
        ListNode* temp = head;
        while(temp != nullptr) {
            if(st.empty()) {
                st.push(temp);
                temp = temp->next;
            }
            else {
                while(!st.empty() && temp->val > st.top()->val)
                    st.pop();
                st.push(temp);
                temp=temp->next;
            }
        }

        ListNode* newHead = nullptr;
        while(!st.empty()) {
            temp  = st.top();
            st.pop();
            temp->next = newHead;
            newHead = temp;
        }

        return newHead;
    }
};

Complexity

Explanation

1. Intuition

2. Implementation


Note: This problem showcases the use of monotonic stack