Skip to content

1019. Next Greater Node In Linked List

https://leetcode.com/problems/next-greater-node-in-linked-list/

js
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var nextLargerNodes = function(head) {
    const arr = []
    while (head) {
        arr.push(head.val)
        head = head.next
    }

    const result = []
    let i = 0
    let j = i + 1

    while (i < arr.length - 1) {
        if (arr[i] < arr[j]) {
            result.push(arr[j])
            i += 1
            j = i + 1
        } else {
            j += 1
            if (j > arr.length - 1) {
                result.push(0)
                i += 1
                j = i + 1
            }
        }
    }

    result.push(0)
    return result
};