summaryrefslogtreecommitdiff
path: root/search/elementary.go
diff options
context:
space:
mode:
authorPaul Buetow <git@mx.buetow.org>2020-12-05 08:35:12 +0000
committerPaul Buetow <git@mx.buetow.org>2020-12-05 08:35:12 +0000
commitd28b47c43ef73efbe06f77acea077bee9ccec492 (patch)
tree24a2bbf5a07936b4e62d36eeaa0f0d756d868a87 /search/elementary.go
parentc8915f36887f82ee9b092393289895338df3d7c0 (diff)
rename set to search
Diffstat (limited to 'search/elementary.go')
-rw-r--r--search/elementary.go79
1 files changed, 79 insertions, 0 deletions
diff --git a/search/elementary.go b/search/elementary.go
new file mode 100644
index 0000000..a9d367e
--- /dev/null
+++ b/search/elementary.go
@@ -0,0 +1,79 @@
+package set
+
+type ElementaryElem struct {
+ key int
+ val int
+ next *ElementaryElem
+}
+
+type Elementary struct {
+ root *ElementaryElem
+}
+
+func NewElementary() *Elementary {
+ return &Elementary{}
+}
+
+func (s *Elementary) Empty() bool {
+ return s.root == nil
+}
+
+func (s *Elementary) Set(key int, val int) {
+ if s.Empty() {
+ s.root = &ElementaryElem{key, val, nil}
+ return
+ }
+
+ elem := s.root
+
+ for {
+ if elem.key == key {
+ elem.val = val
+ return
+ }
+ if elem.next == nil {
+ elem.next = &ElementaryElem{key, val, nil}
+ return
+ }
+ elem = elem.next
+ }
+}
+
+func (s *Elementary) Get(key int) (int, error) {
+ elem := s.root
+
+ for elem != nil {
+ if elem.key == key {
+ return elem.val, nil
+ }
+ elem = elem.next
+ }
+
+ return 0, NotFound
+}
+
+func (s *Elementary) Del(key int) (int, error) {
+ if s.Empty() {
+ return 0, NotFound
+ }
+
+ if s.root.key == key {
+ defer func() {
+ s.root = s.root.next
+ }()
+ return s.root.val, nil
+ }
+
+ elem := s.root
+ for elem.next != nil {
+ if elem.next.key == key {
+ defer func() {
+ elem.next = elem.next.next
+ }()
+ return elem.next.val, nil
+ }
+ elem = elem.next
+ }
+
+ return 0, NotFound
+}