DEV Community

Karleb
Karleb

Posted on

#2487. Remove Nodes From Linked List

https://leetcode.com/problems/remove-nodes-from-linked-list/?envType=daily-question&envId=2024-05-06


/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var removeNodes = function (head) {
    let stack = []
    let curr = head

    while (curr) {
        while (stack.length && curr.val > stack[stack.length - 1]) {
            stack.pop()
        }
        stack.push(curr.val)
        curr = curr.next
    }

    //This converts the stack into a linkedlist
    let dummy = new ListNode()
    let dummyCurr = dummy

    for (let val of stack) {
        dummyCurr.next = new ListNode(val)
        dummyCurr = dummyCurr.next
    }

    return dummy.next
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)