In this tutorial, we are going to learn about InsertAfter() function in list package in go golang. InsertAfter() function is used to insert a new element immediately after given node in function parameter in go golang.
Function proto type:
func (l *List) InsertAfter(value interface{}, ele *Element) *Element
InsertAfter() function:
InsertAfter() function inserts a new element immediately after given node in
function parameter. If node given in function parameter is missing in list,
then list will not get modified.
It returns the pointer of new inserted element.
Example to use InsertAfter() function in list:
package main
import (
"container/list"
"fmt"
)
func main() {
var ele *list.Element
// Create a new list and insert elements in it.
l := list.New()
l.PushBack(1)
l.PushBack(2)
l.PushBack(3)
l.PushBack(4)
fmt.Println("Print list before inserting element: ")
for ele = l.Front(); ele != nil; ele = ele.Next() {
fmt.Println(ele.Value)
}
/* To reach the node where the value is to be inserted
after given node */
for ele = l.Front(); ele.Value != 3; ele = ele.Next() {}
/* Insert element with value 10 after element with value 3
in list */
ele = l.InsertAfter(10, ele)
fmt.Println("Print list after inserting element: ")
for ele = l.Front(); ele != nil; ele = ele.Next() {
fmt.Println(ele.Value)
}
}
Output:
Print list before inserting element:
1
2
3
4
Print list after inserting element:
1
2
3
10
4
To learn more about golang, Please refer given below link:
https://techieindoor.com/go-lang-tutorial/
References:
https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
https://golang.org/pkg/container/list/