The list is a double linked list of Elements. Element is an element in the linked list with Next() and Prev() pointer to other elements. Begining and ending of Elements are nil.
package main
import (
. "fmt";
"container/list";
"strings";
"bytes";
)
// print the elements of the list
func PrintList(l *list.List) {
Println("------------------------------");
for value := range l.Iter() {
Println("element: ", value);
}
Println("------------------------------");
}
func main() {
// create a new list
li := list.New();
// add elements at end
li.PushBack("list1");
li.PushBack("list2");
// add elements at begining
li.PushFront("list3");
PrintList(li);
// get the first element from the list
element := li.Front();
str := element.Value;
Println("value: ", str);
// add a element before the first element
li.InsertBefore("list4", element);
// add after the element
li.InsertAfter("list5", element);
PrintList(li);
// get the next element
element = element.Next();
Println("value: ", element.Value);
// move the first element to back
element = li.Front();
li.MoveToBack(element);
PrintList(li);
// remove the first element
element = li.Front();
li.Remove(element);
PrintList(li);
// find the element with "list2" and remove it
for element := li.Front(); element != nil; element = element.Next() {
// don't use li.Iter(), because the interface chanel
// is geting the Value from the element back. not the element.
value := element.Value.(string);
if bytes.Equal(strings.Bytes(value),strings.Bytes("list2")) {
li.Remove(element);
}
}
PrintList(li);
}
the output is:
------------------------------
element: list3
element: list1
element: list2
------------------------------
value: list3
------------------------------
element: list4
element: list3
element: list5
element: list1
element: list2
------------------------------
value: list5
------------------------------
element: list3
element: list5
element: list1
element: list2
element: list4
------------------------------
------------------------------
element: list5
element: list1
element: list2
element: list4
------------------------------
------------------------------
element: list5
element: list1
element: list4
------------------------------
Keine Kommentare:
Kommentar veröffentlichen