/**
* 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 *> st;
for (ListNode *it = head; it != nullptr; it = it->next) {
while (!st.empty() && st.top()->val < it->val) {
ListNode *x = st.top();
st.pop();
delete x;
}
st.push(it);
}
ListNode *dummy = new ListNode(), *curr = dummy;
while (!st.empty()) {
st.top()->next = nullptr;
curr->next = st.top();
curr = curr->next;
st.pop();
}
curr = dummy->next;
delete dummy;
// Reverse the linked list.
ListNode *newHead = nullptr;
while (curr != nullptr) {
ListNode *x = curr->next;
curr->next = newHead;
newHead = curr;
curr = x;
}
return newHead;
}
};
My Solution Solution 1: DFS (recursion) The Key Idea for Solving This Coding Question C++ Code /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right;
Jun 6, 2025MyCircularQueueO(k)
Apr 20, 2025O(m)
Mar 4, 2025O(n)n is the length of nums.
Feb 19, 2025or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up