Menu Close

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

In this tutorial, we are going to learn about MoveToBack() function in list package in go golang. MoveToBack() function is used to move given list node to the back of the list in go golang.

Function proto type:

func (l *List) MoveToBack(ele *Element) 

MoveToBack() function:

MoveToBack() function moves element “ele” to the back of the list.
If ele is not an element in list, then list will not get modified. 

Example:

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

After applying MoveToBack() function in list for value 3

list.MoveToBack(3)

list = 1 -> 2 -> 4 -> 5 -> 3
// 3 moves at the end

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

Example to use MoveToBack() 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) // 1
  l.PushBack(2) // 1 -> 2
  l.PushBack(3) // 1 -> 2 -> 3
  l.PushBack(4) // 1 -> 2 -> 3 -> 4
  l.PushBack(5) // 1 -> 2 -> 3 -> 4 -> 5

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

    fmt.Println(ele.Value)
    
  }

  // To move back ele with value 3
  for ele = l.Front(); ele.Value != 3; ele = ele.Next() {}

  l.MoveToBack(ele)

  // Now list is: 1 -> 2 -> 4 -> 5 -> 3

  fmt.Println("Print list after moving element")

  for ele = l.Front(); ele != nil; ele = ele.Next() {

    fmt.Println(ele.Value)
    
  }
}

Output:

 Print list before moving element
1
2
3
4
5
Print list after moving element
1
2
4
5
3

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

https://techieindoor.com/go-lang-tutorial/
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/
Posted in golang, list package

Leave a Reply

Your email address will not be published. Required fields are marked *