Menu Close

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

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

Function proto type:

func (list_1 *List) PushBackList(list_2 *List) 

PushBackList() function:

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

Example:

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

after applying PushBackList() function in list_1 for list_2:

list_1.PushBackList(list_2)

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

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

Example to use PushBackList() 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 back using
    PushBackList function */
     
  list_1.PushBackList(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:
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