Change queues and stacks

- Make chain element private
- Remove JSON Marshaller from stack and queue
- Remove access to top chain element
This commit is contained in:
Melody Becker 2025-04-24 15:52:43 +02:00
parent 9870d87d41
commit 09de0a19e1
Signed by: mstar
SSH key fingerprint: SHA256:9VAo09aaVNTWKzPW7Hq2LW+ox9OdwmTSHRoD4mlz1yI
3 changed files with 18 additions and 52 deletions

View file

@ -1,13 +1,15 @@
package containers
import (
"encoding/json"
"errors"
)
var ErrInvalidQueue = errors.New("invalid queue")
var ErrEmptyQueue = errors.New("empty queue")
type Queue[T any] struct {
head *ChainElem[T]
tail *ChainElem[T]
head *chainElem[T]
tail *chainElem[T]
}
// isValid checks if the queue is still valid.
@ -25,7 +27,7 @@ func (q *Queue[T]) IsEmpty() bool {
// Push adds a new element to the end of the queue.
func (q *Queue[T]) Push(elem *T) error {
if !q.isValid() {
return errors.New("invalid queue")
return ErrInvalidQueue
}
e := emptyElem[T]()
@ -40,10 +42,10 @@ func (q *Queue[T]) Push(elem *T) error {
// It errors out if there is no element or the queue is invalid.
func (q *Queue[T]) Pop() (*T, error) {
if !q.isValid() {
return nil, errors.New("invalid queue")
return nil, ErrInvalidQueue
}
if q.IsEmpty() {
return nil, errors.New("empty queue")
return nil, ErrEmptyQueue
}
Elem := q.head.Elem
q.head = q.head.Next
@ -54,38 +56,14 @@ func (q *Queue[T]) Pop() (*T, error) {
// It errors out if there is no element or the queue is invalid.
func (q *Queue[T]) Top() (*T, error) {
if !q.isValid() {
return nil, errors.New("queue invalid")
return nil, ErrInvalidQueue
}
if q.IsEmpty() {
return nil, errors.New("queue empty")
return nil, ErrEmptyQueue
}
return q.head.Elem, nil
}
// HeadElem returns the first ChainElem of the queue without removing it.
// It errors out if there is no element or the queue is invalid.
func (q *Queue[T]) HeadElem() (*ChainElem[T], error) {
if !q.isValid() {
return nil, errors.New("queue invalid")
}
if q.IsEmpty() {
return nil, errors.New("queue empty")
}
return q.head, nil
}
// MarshalJSON is used for generating json data when using json.Marshal.
func (q *Queue[T]) MarshalJSON() ([]byte, error) {
if !q.isValid() {
return nil, errors.New("queue invalid")
}
if q.IsEmpty() {
return nil, errors.New("queue empty")
}
return json.Marshal(q.head)
}
func BuildQueue[T any]() *Queue[T] {
empty := emptyElem[T]()
return &Queue[T]{