Skip to content

Instantly share code, notes, and snippets.

@artisonian
Created Aug 10, 2019
Embed
What would you like to do?
// see http://www.eprg.org/computerphile/tripref.c
package main
import (
"fmt"
"strings"
)
type thing struct {
item string
next *thing
}
type list struct {
tracer **thing
}
func newList() list {
var head *thing
return list{&head}
}
// insert adds new element into a singly-linked list.
// **Note**: It does not check for duplicate elements.
func (l list) insert(s string) {
t := &thing{item: s}
for *l.tracer != nil && (*l.tracer).item < t.item {
l.tracer = &(*l.tracer).next
}
t.next = *l.tracer
*l.tracer = t
}
// remove deletes the first element on list whose item field matches the given text.
// **NOTE**: It ignores elements not present in the list.
func (l list) remove(s string) {
present := (*l.tracer).item == s
for *l.tracer != nil && !present {
l.tracer = &(*l.tracer).next
present = (*l.tracer).item == s
}
if present {
*l.tracer = (*l.tracer).next
}
}
func (l list) String() string {
var b strings.Builder
for *l.tracer != nil {
b.WriteString((*l.tracer).item + " ")
l.tracer = &(*l.tracer).next
}
return b.String()
}
func main() {
l := newList()
l.insert("chips")
l.insert("wine")
l.insert("burgers")
l.insert("beer")
l.insert("pizza")
l.insert("zucchini")
l.insert("burgers")
l.insert("slaw")
fmt.Printf("Initial list: %s\n", l)
l.remove("pizza")
l.remove("zucchini")
l.remove("burgers")
fmt.Printf("Altered list: %s\n", l)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment