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.

Function proto type:

func (l *List) MoveBefore(src_ele, dst_ele *Element) 

MoveBefore() function:

MoveBefore() function moves src_ele node to before dst_ele node.
If src_ele and dst_ele nodes are same then list will not get modified. 

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

Internal code of MoveBefore() function in list package:

func (l *List) MoveBefore(src_ele, dst_ele *Element) {

    if src_ele.list != l || src_ele == dst_ele || dst_ele.list != l {

        return
    }

    l.move(src_ele, dst_ele.prev)
}

Example to use MoveBefore() function in list:

package main

import (
        "container/list"
        "fmt"
)

func main() {
        var ele, src_ele, dst_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)
        }

        // Keep src_ele pointer variable at element with value 4
        for src_ele = l.Front(); src_ele.Value != 4; src_ele = src_ele.Next() {}

        // Keep dst_ele pointer variable at element with value 2
        for dst_ele = l.Front(); dst_ele.Value != 2; dst_ele = dst_ele.Next() {}

        // move element with value 4 to before element with value 2
        l.MoveBefore(src_ele, dst_ele)

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

        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
4
2
3
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.

Contact Us