package main /** * A fairly simple implementation of a single linked list in Go * Created: Sep 2023 * Author gtowell */ import "fmt" // a struct for the Node of a linked list. // The data item should be generic type Node struct { next *Node data int } // A struct to hold the head and tail of a linked list. // most LL methods will be from here type LinkedList struct { head *Node tail *Node } // Add an item to the linked list. // This will change the tail, and may change the head func (ll *LinkedList) add(dta int) { nnode := Node{data:dta} fmt.Printf("Add %v\n", nnode) if ll.head==nil { fmt.Println("Enpty list") ll.head=&nnode ll.tail=&nnode } else { ll.tail.next = &nnode ll.tail=&nnode } } // A function type, for easy reference later type itrfunc func() *Node // ask the linked list for an iterator // this will give each node in the list // successively func (ll LinkedList) getIterator() itrfunc { var nxt *Node frst := true return func() *Node { if nxt==nil { if frst { nxt=ll.head return nxt } else { return nil; } } else { nxt = nxt.next return nxt } } } //Exercise the linked list func main() { ll := LinkedList{} ll.add(1) fmt.Printf("HH %v\n", ll.head) ll.add(3) ll.add(5) ll.add(7) for getNext:=ll.getIterator();; { v:=getNext() if v==nil { break; } fmt.Printf("%v\n", v.data) } }