Menu Close

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

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

Function proto type:

func (list_1 *List) PushFrontList(list_2 *List) 

PushFrontList() function:

PushFrontList() function inserts a copy of another list at the front of list.
Both the lists may be the same but must not be nil.

Example:

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

After apply PushFrontList() function:

list_1.PushFrontList(list_2)

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

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

Example to use PushFrontList() function in list:

package main

import (
  "container/list"
  "fmt"
)

func main() {
    
  var ele *list.Element

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

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

  list_2.PushBack(3) // 3
  list_2.PushBack(4) // 3 -> 4

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

    fmt.Println(ele.Value)
    
  }

  fmt.Println("Print list_2")
  for ele = list_2.Front(); ele != nil; ele = ele.Next() {

    fmt.Println(ele.Value)
    
  }

   /* insert list_2 to list_1 at the front 
     using PushFrontList function */
  list_1.PushFrontList(list_2)

  fmt.Println("Print list_1 after inserting list_2 in it: ")
  for ele = list_1.Front(); ele != nil; ele = ele.Next() {

    fmt.Println(ele.Value)
    
   }

}

Output:

 Print list_1
1
2

Print list_2
3
4

Print list_1 after inserting list_2 in it:
3
4
1
2

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