Created
February 15, 2020 23:00
-
-
Save bergwerf/6fae0fea3f4f203999c6fe77434c9f64 to your computer and use it in GitHub Desktop.
Golang ordered sets using container/list
This file contains hidden or 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
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