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:
parent
9870d87d41
commit
09de0a19e1
3 changed files with 18 additions and 52 deletions
|
@ -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]{
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue