Menu Close

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

In this tutorial, we are going to learn about PushFront() function in list package in go golang. PushFront() function is used to insert a new element at the front of list in go golang.

Function proto type:

func (l *List) PushFront(value interface{}) *Element 

PushFront() function:

PushFront() function inserts a new element at the front of list.
This function returns pointer of newly inserted element. 

Example:

list_1 = 1 -> 2 -> 3 -> 4

list_1.
PushFront(5)

list_1 =
5 -> 1 -> 2 -> 3 -> 4

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

Example to use PushFront() function in list:

package main

import (
  "container/list"
  "fmt"
)

func main() {
    
  var ele *list.Element

  // Create list and insert elements in it.
  list_1 := list.New()

  list_1.PushBack(1) // 1
  list_1.PushBack(2) // 1 -> 2
  list_1.PushBack(3) // 1 -> 2 -> 3
  list_1.PushBack(4) // 1 -> 2 -> 3 -> 4


  fmt.Println("Print list before inserting element")
  for ele = list_1.Front(); ele != nil; ele = ele.Next() {

    fmt.Println(ele.Value)
    
  }

  list_1.PushFront(5)
  // Now list: 5 -> 1 -> 2 -> 3 -> 4

  fmt.Println("Print list after inserting element")
  for ele = list_1.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
5
1
2
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