[LeetCode] Remove Nodes From Linked List

2487. Remove Nodes From Linked List

You are given the head of a linked list.

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

Return the head of the modified linked list.

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
/**
* 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) {
vector<int> st;
ListNode* runner = head;
while(runner) {
while(st.size() and st.back() < runner->val) {
st.pop_back();
}
st.push_back(runner->val);
runner = runner->next;
}
ListNode* dummy = new ListNode(-1);
ListNode* tail = dummy;
for(int i = 0; i < st.size(); i++) {
ListNode* now = new ListNode(st[i]);
tail->next = now;
tail = now;
}
return dummy->next;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/27/PS/LeetCode/remove-nodes-from-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.