题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个链表,现在对于每个节点,要找下一个比它更大的节点的值。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverse(self, head):
pre = None
cur = head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre

def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
head = self.reverse(head)
ans = []
st = []
while head:
while st and st[-1] <= head.val:
st.pop()
ans.append(st[-1] if st else 0)
st.append(head.val)
head = head.next
return ans[::-1]