Leetcode 1072 Solution

This article provides solution to leetcode question 1072 (next-greater-node-in-linked-list)

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

Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def nextLargerNodes(self, head: ListNode) -> List[int]:
        if not head:
            return None

        a = []
        node = head
        while node:
            a.append(node.val)
            node = node.next

        s = []
        b = []
        for i in reversed(range(len(a))):
            while s and s[-1] <= a[i]:
                s.pop(-1)

            b.append(0 if len(s) == 0 else s[-1])
            s.append(a[i])

        node = None
        for i, v in enumerate(b):
            curr = ListNode(v)
            curr.next = node
            node = curr
        return node