Created
August 10, 2019 14:16
-
-
Save artisonian/b825ad581d72ac6937c25ea23a510ad1 to your computer and use it in GitHub Desktop.
Triple Ref Pointers: https://www.youtube.com/watch?v=0ZEX_l0DFK0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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