Skip to content

Instantly share code, notes, and snippets.

@bergwerf
Created February 15, 2020 23:00
Show Gist options
  • Save bergwerf/6fae0fea3f4f203999c6fe77434c9f64 to your computer and use it in GitHub Desktop.
Save bergwerf/6fae0fea3f4f203999c6fe77434c9f64 to your computer and use it in GitHub Desktop.
Golang ordered sets using container/list
package main
import "container/list"
// ListUnion merges the second list into the first list while retaining order.
func ListUnion(dst *list.List, src *list.List) {
for e1, e2 := src.Front(), dst.Front(); e2 != nil; {
if e1 == nil {
dst.PushBack(e2.Value)
e2.Next()
continue
}
v1, v2 := e1.Value.(uint), e2.Value.(uint)
if v1 == v2 {
e2.Next()
} else if v1 < v2 {
e1.Next()
} else {
dst.InsertBefore(v2, e1)
}
}
}
// Convert list to uint slice.
func toSlice(l *list.List) []uint {
output := make([]uint, 0, l.Len())
for ptr := l.Front(); ptr != nil; ptr = ptr.Next() {
output = append(output, ptr.Value.(uint))
}
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment