package main import "fmt" // The start of a linked list in Go. // And some review of pointers // Created: 11/15/2022 gtowell // A node in a linked list. Note that the type of the "data" // could be anything at all, and would usually be another struct type LL struct { dta dataStruct nxt *LL // * indicated that what is stored here is an address } // a struct holding data in the linked list // Unnecessary in this case as the struct is minimal type dataStruct struct { dta int16 } // toString method for the struct dataStruct func (dta dataStruct) String() string { return fmt.Sprintf("%d", dta.dta) } // returns the last 4 digits of the pointer contained in the // linked list node func (mll *LL) l4a() string { a:= fmt.Sprintf("%p", mll) return a[len(a)-4:]; } // method to print a one line representation of a LinkedList // header is some string to identify the particular list func (mll *LL) printLL(header string) { fmt.Printf("%s: ", header) for ;mll!=nil; { fmt.Printf("[%s]--> %d ", mll.l4a(), mll.dta) mll=mll.nxt } fmt.Printf("\n") } func main() { a := LL{dta: dataStruct{5}} b := new(LL) // new pretty much guarantees allocation from heap // "new(LL)" makes an instance of LL much line LL{ }, but the initial values are all zeroes. b.dta = dataStruct{10} a.nxt = b fmt.Printf("Create A then B, and append B to A\n") (&a).printLL("A"); b.printLL("B"); c := LL{dta: dataStruct{20}} c.nxt = &a; // again & get address fmt.Printf("Create C and append A onto C\n") c.printLL("C"); }