# 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 []
#单调栈
stack = []
#记录每个元素的下标
stack_loc = []
loc = 0
#存放结果
res = []
while head:
#首先给这个res数组都添加0,如果有改变就直接将0替换掉
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)
#下标加1
loc += 1
#head指向下个节点
head = head.next
#返回结果数组
return res
分析
- 维护一个单调栈就不用n次遍历了
- 降低了暴力解法的时间复杂度
总结:单调栈+链表之前没有做过这种题,单调栈大大的降低了遍历的时间复杂度。