This question already has an answer here:
I would like to know if there is any way by which I can create dynamically sized array to avoid runtime error in the code below.
Error:
panic: runtime error: index out of range in Go
Code:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func nextLargerNodes(head *ListNode) []int {
var a []int
var pha int
hNum := 0
currNode := head
pha = 0
for currNode.Next != nil {
iter := currNode.Next
hNum = currNode.Val
//phb = pha + 1
for(iter.Next != nil){
if hNum < iter.Val {
hNum = iter.Val
break
} else if hNum == iter.Val{
hNum = 0
break
}
iter = iter.Next
}
a[pha] = iter.Val
pha++
hNum = 0
currNode = currNode.Next
}
return a
}
</div>
You should use append function.
var a []int
is a slice, you can think of it as a "dynamic array". In order to add elements to it, you should use append method. In your code, you used array semantics.
a = append(a, iter.Val)
You can create your slice with a predefined number of elements if you know upfront how many elements you are going to have in your slice.
a := make([]int, 10)
this will create a slice with 10 elements in it.
Go arrays are fixed in size, but thanks to the builtin append method, we get dynamic behavior. The fact that append returns an object, really highlights the fact that a new array will be created if necessary. The growth algorithm that append uses is to double the existing capacity.
numbers := make([]int, 0)
numbers = append(numbers, 1)
numbers = append(numbers, 2)
fmt.Println(len(numbers)) // == 2