1019. Next Greater Node In Linked List
- Next Greater Node In Linked List python solution
题目描述
We are given a linked list with head as the first node. Let’s number the nodes in the list: node_1, node_2, node_3, … etc.
Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice. If such a j does not exist, the next larger value is 0.
Return an array of integers answer, where answer[i] = next_larger(node_{i+1}).
Note that in the example inputs (not outputs) below, arrays such as [2,1,5] represent the serialization of a linked list with a head node value of 2, second node value of 1, and third node value of 5.
解析
题目的意思是,给定单链表,我们需要找到每个节点后面第一个比它大的元素。如果不存在就为0。将这些元素组成一个新的序列并返回。
为了保证数列的相对位置不变,我们使用栈来进行操作。需要保存两种信息,第一个是该元素所在位置,第二个是该元素的大小。
如果遇到了一个数字n比栈顶元素stack[-1]为下标的数字更大时,需要一直退栈,这样就保证不会被多次更新,只记录第一个比自己大的元素。退栈到栈顶元素大于等于目前元素为止。
res数组记录最终结果,然后stack栈作为更新的指引,避免更新过的元素被二次更新,从而保证只记录第一个比自己大的元素。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def nextLargerNodes(self, head):
res,stack=[],[]
while head:
while stack and stack[-1][1]<head.val:
res[stack.pop()[0]]=head.val
stack.append([len(res),head.val])
res.append(0)
head=head.next
return res
Reference
https://leetcode.com/problems/next-greater-node-in-linked-list/discuss/265508/JavaC%2B%2BPython-Next-Greater-Element