Menu Close

Go – InsertBefore() function in list package in go golang

In this tutorial, we are going to learn about InsertBefore() function in list package in go golang. InsertBefore() function is used to insert a new element immediately before given node in function parameter in go golang.

Function proto type:

func (l *List) InsertBefore(value interface{}, ele *Element) *Element 

InsertBefore() function:

InsertBefore() function inserts a new element immediately before 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. 

To learn more about list package in go, Please follow this link

Example to use InsertBefore() 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
     before that node */
     
  for ele = l.Front(); ele.Value != 3; ele = ele.Next() {}

  /* Insert element with value 10 before element with
     value 3 in list */
     
  ele = l.InsertBefore(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
10
3
4

To learn more about golang, Please refer given below link:

https://www.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/
Posted in golang, list package

Leave a Reply

Your email address will not be published.

Contact Us