LeetCode 1019. Next Greater Node In Linked List - 单调栈(Monotonic Stack)系列题5

You are given the head of a linked list with n nodes.

For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.

Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.

Example 1:

Input: head = [2,1,5]
Output: [5,5,0]

Example 2:

Input: head = [2,7,4,3,5]
Output: [7,0,5,5,0]

Constraints:

  • The number of nodes in the list is n.
  • 1 <= n <= 104
  • 1 <= Node.val <= 109

这题是给定一个链表,然后要求链表中每个节点值的下一个更大值(Next Great Node),最后返回一个数组,数组中每个数对应的是链表从头到尾每个节点的下个更大节点值(不存在的为0)。

最简单的解法就是遍历链表,把链表转换成一个数组,然后就跟496. Next Greater Element的解法一样了。要是这样的话,这题难度系数就应该是easy了,因此得想办法通过一次遍历就把事情给办了。

基本思路还是利用单调递减栈, 跟496. Next Greater Element不同是,事先不知道链表节点的个数也就无法知道答案数组answer的大小(初始化只能为空)。因此要定义一个从0开始计数变量,每次遍历到一个新节点答案数组answer就添加一个数(值为0),计数变量就加1,这样这个计数变量就把答案数组answer的索引跟链表节点顺序对应上了。堆栈里要同时放入节点值和计数变量值(即answer的索引)。剩下的就跟496. Next Greater Element一样了。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
        res = []
        cur = head
        st = []
        i = 0
        
        while cur:
            res.append(0)
            while st and st[-1][0] < cur.val:
                res[st.pop()[1]] = cur.val
            st.append((cur.val, i))
            i += 1
            cur = cur.next
            
        return res

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值