Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2487. Remove Nodes From Linked List

Rain Hu

2487. Remove Nodes From Linked List


一、題目

You are given the head of a linked list.
Remove every node which has a node with strictly greater value anywhere to the right side of it.
Return the head of the modified linked list.

Example 1:
drawio

Example 2:

Constraints:


二、分析

三、解題

1. Monotonic Stack

ListNode* removeNodes(ListNode* head) {
    deque<ListNode*> dq;
    dq.push_back(new ListNode(INT_MAX, head));  // 省去處理 deque 為空的狀況
    ListNode* curr = head;
    while (curr) {
        while (curr->val > dq.back()->val) {
            dq.pop_back();
        }
        dq.push_back(curr);
        curr = curr->next;
    }
    ListNode* dummy = new ListNode(dq.front()->val);
    curr = dummy;
    dq.pop_front();
    while (!dq.empty() && curr) {
        curr->next = dq.front();
        dq.pop_front();
        curr = curr->next;
    }
    return dummy->next;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2488. Count Subarrays With Median K
Next
[LeetCode] 2486. Accept Characters to String to Make Subsequence