Container list in Golang

PROGRAM:

package main

import (
"container/list"
"fmt"
)

func displayList(l *list.List) {
/* Traverse the list */
for e := l.Front(); e != nil; e = e.Next() {
fmt.Printf("%d ", e.Value)
}
fmt.Printf("\n")
}

func removeList(l *list.List, data int) {
/* Traverse the list and check */
for e := l.Front(); e != nil; e = e.Next() {
if e.Value == data {
l.Remove(e)
}
}
}

func main() {
/* Create the list */
mylist := list.New()

/* Push element at end */
mylist.PushBack(10)
mylist.PushBack(20)
fmt.Printf("Count-%d: ", mylist.Len())
displayList(mylist)

/* Push element at first */
mylist.PushFront(13)
mylist.PushFront(17)
fmt.Printf("Count-%d: ", mylist.Len())
displayList(mylist)

/* Remove element from list */
removeList(mylist, 10)
fmt.Printf("Count-%d: ", mylist.Len())
displayList(mylist)

/* Clear the list */
mylist.Init()
fmt.Printf("Count-%d: ", mylist.Len())
displayList(mylist)
}

OUTPUT:

sujin@sujin:~/workspace/go$ go build list.go

sujin@sujin:~/workspace/go$ ./list
Count-2: 10 20 
Count-4: 17 13 10 20 
Count-3: 17 13 20 
Count-0: 

No comments:

Post a Comment