1019. 链表中的下一个更大节点

示例 1:

输入:[2,1,5]
输出:[5,5,0]
示例 2:

输入:[2,7,4,3,5]
输出:[7,0,5,5,0]
示例 3:

输入:[1,7,5,1,9,2,5,1]
输出:[7,9,9,9,0,5,0,0]

方法一:转成数组操作

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def nextLargerNodes(self, head: ListNode):
        nums = []
        node = head
        while node != None :
            nums.append(node.val)
            node = node.next
        stack = []
        stack_loc = []
        res = [0] * len(nums)

        for i in range(len(nums)):
            while stack and stack[-1] < nums[i]:
                res[stack_loc[-1]] = nums[i]
                stack.pop()
                stack_loc.pop()
            stack.append(nums[i])
            stack_loc.append(i)

        return res
print(Solution().nextLargerNodes(head=0))
"""遍历2,由于2是第一个数,直接入栈。2比一小吗?否,1入栈。1比5小吗?是。1的下一个大数是5.弹出1;2比5小吗,是,2的下一个最大值是5.弹出2.
栈空了。5入栈,5比7小吗,是,5的下一个最大数是7,弹出5,7入栈。7是最后一个元素。for循环结束。"""

方法二:直接操作链表(有空再看)

class Solution:
    def nextLargerNodes(self, head: ListNode) -> List[int]:        
        stack = []
        stack_loc = []
        loc = -1
        res = []
        while head:
            loc += 1
            res.append(0)
            while stack and stack[-1] < head.val:
                res[stack_loc[-1]] = head.val
                stack.pop()
                stack_loc.pop()
            stack.append(head.val)
            stack_loc.append(loc)
            
            head = head.next

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值