链表中的下一个更大节点

给出一个以头节点 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;
  }
View Code

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-node-in-linked-list

原文地址:https://www.cnblogs.com/wuyouwei/p/11839246.html