Leetcode1019. Next bigger node in linked list (golang)

1. Topic

Source of the topic: https://leetcode-cn.com/problems/next-greater-node-in-linked-list/

Given a linked list with the head node headas the first node. The nodes in the linked list are respectively numbered: node_1, node_2, node_3, ....

Each node may have the next larger value ( next larger value ): for node_i, if it next_larger(node_i)is node_j.val, then there is j > iand node_j.val > node_i.val, but jis the smallest possible option. If no such exists j, then the next greater value is 0.

Returns an array of integer answers answerwhere answer[i] = next_larger(node_{i+1}).

Note: In the example below, [2,1,5]an input such as this (not an output) is a serialized representation of a linked list with the value 2 for the head node, 1 for the second node, and 5 for the third node.

  • Example 1:

Input: [2,1,5]
Output: [5,5,0]

  • Example 2:

Input: [2,7,4,3,5]
Output: [7,0,5,5,0]

  • Example 3:

Input: [1,7,5,1,9,2,5,1]
Output: [7,9,9,9,0,5,0,0]

  • hint:

For each node in the linked list, 1 <= node.val <= 10^9
The length of the given list is in the range [0, 10000]

Two, solution

Solve using a monotonic stack:

For specific ideas, see the author's diagram and code comments

The diagram is as follows:

insert image description here

the code

func nextLargerNodes(head *ListNode) []int {
    
    
	//首先遍历链表,将链表的值入数组arr
    var arr []int
    for head != nil{
    
    
        arr = append(arr, head.Val)
        head = head.Next
    }
    //定义最后的返回数组result和栈stack,长度为链表也就是arr的长度
    //注意:go语言中int类型默认值为0,[]int,即默认为[0]
    result, stack := make([]int, len(arr)), make([]int, len(arr))
    //遍历数组arr
    for index := 0; index < len(arr); index++{
    
    
        //当栈为空的时候将数组下标入栈
        //之所以入下标而不直接入值是为了在result中找到并修改对应index下标的位置
        if len(stack) == 0{
    
    
            stack = append(stack, index)
        }else{
    
      //如果栈中已有元素,那么开始循环比较
            //若此时的index对应的值大于stack栈顶元素坐标对应的值,就将栈顶元素出栈
            for len(stack) > 0 && arr[index] > arr[stack[len(stack)-1]]{
    
    
                //将栈顶元素坐标赋给pop,用于出栈
                pop := len(stack) - 1
                //并改变result中对应栈顶元素坐标位置的值为index对应值(也就是当前最大值)
                result[stack[pop]] = arr[index]
                //弹出栈顶元素
                stack = stack[:pop]
            }
            //循环完毕,直至栈中没有比index对应值更大的数,就将该最大值坐标index入栈
            stack = append(stack, index)
        }
        
    }
    //返回result
    return result
}

Guess you like

Origin blog.csdn.net/QQ395879676/article/details/115640910