給出一個以頭節點 head 作為第一個節點的鏈表。鏈表中的節點分別編號為:node_1, node_2, node_3, ... 。
每個節點都可能有下一個更大值(next larger value):對於 node_i,如果其 next_larger(node_i) 是 node_j.val,那么就有 j > i 且 node_j.val > node_i.val,而 j 是可能的選項中最小的那個。如果不存在這樣的 j,那么下一個更大值為 0 。
返回整數答案數組 answer,其中 answer[i] = next_larger(node_{i+1}) 。
注意:在下面的示例中,諸如 [2,1,5] 這樣的輸入(不是輸出)是鏈表的序列化表示,其頭節點的值為 2,第二個節點值為 1,第三個節點值為 5 。
示例 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]
提示:
對於鏈表中的每個節點,1 <= node.val <= 10^9
給定列表的長度在 [0, 10000] 范圍內
解法1:

public static int[] nextLargerNodes2(ListNode head) { /*鏈表中的位置對應的后面一個節點比它大的下表*/ List<Integer> indexList = new ArrayList<>(); /*鏈表中的值*/ List<Integer> headList = new ArrayList(); ListNode itr = head; int count = 0; while (itr != null) { count++; if (itr.next != null && itr.next.val > itr.val) { /*當后一個節點比前一個大時,記錄后一個節點的下標,第一個鏈表節點0對應的后一個比它大的下標就是1*/ indexList.add(count); } else { /*不大於塞0*/ indexList.add(0); } /*保存節點的值*/ headList.add(itr.val); /*移向下一個節點*/ itr = itr.next; } /*構建數組*/ int[] re = new int[count]; int i; int j = 0; for (i = count - 2; i >= 0; i--) { /*從倒數第二個節點開始對比其后一個節點是否比它大,如果是,則直接取對應節點值,從headList里找出來放入數組中*/ int index = indexList.get(i); if (index != 0) { re[i] = headList.get(index); /*j指向最大值下標*/ j = index; } else { /*如果獲取到的是0,說明后一個節點不比當前節點大,則找后面的節點,直到找到比當前節點值大的為止*/ while (j != 0 && headList.get(j) <= headList.get(i)) { /*找下一個節點比當前值大的下標*/ j = indexList.get(j); } indexList.set(i, j); re[i] = (j == 0) ? 0 : headList.get(j); } } return re; }
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/next-greater-node-in-linked-list