Menu Close

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

In this tutorial, we are going to learn about MoveAfter() function in list package in go golang. MoveAfter() function is used to move source element node to after destination element node in go golang.

Function proto type:

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

MoveAfter() function:

MoveAfter() function moves src_ele node to after 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

Example to use MoveAfter() 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 2
  for src_ele = l.Front(); src_ele.Value != 2; src_ele = src_ele.Next() {}

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

  // move element with value 2 to after element with value 4
  l.MoveAfter(src_ele, dst_ele)

  // Now list is: 1 -> 3 -> 4 -> 2 -> 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
3
4
2
5

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 *