Menu Close

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

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

Function proto type:

func (l *List) MoveBefore(ele, mark *Element)

MoveBefore() function:

MoveBefore() function in list moves element e to its new position before mark. If ele or mark is not an element of l, or ele == mark, the list is not modified. The element and mark must not be nil.

Example:

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

After applying MoveBefore()function in list for value 3 and 2

ele = 3
mark = 2

list.MoveBefore(ele, mark)

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

Example with code:

package main

import (
  "container/list"
  "fmt"
)

func main() {
  var ele, mark *list.Element

  // Create a new list and insert elements in it.
  l := list.New()

  // 1
  l.PushBack(1)

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

  // 1 -> 2 -> 3
  l.PushBack(3)

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

  // 1 -> 2 -> 3 -> 4 -> 5
  l.PushBack(5)


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

    fmt.Println(tmp.Value)

  }

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

  for mark = l.Front(); mark.Value != 2; mark = mark.Next() {}

  l.MoveBefore(ele, mark)

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

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

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

    fmt.Println(tmp.Value)
  }
}

Output:

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

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. Required fields are marked *