github.com/djordje200179/extendedlibrary/datastructures@v1.7.1-0.20240227175559-d09520a92dd4/seqs/colseq/deque.go (about) 1 package colseq 2 3 import ( 4 "github.com/djordje200179/extendedlibrary/datastructures/cols" 5 "github.com/djordje200179/extendedlibrary/datastructures/cols/array" 6 "github.com/djordje200179/extendedlibrary/datastructures/cols/linklist" 7 ) 8 9 // Deque is a double-ended queue. 10 // It is a sequence of elements in which items can be inserted or removed from either the front or back. 11 // Pushing is always possible, but popping and peeking panics if the deque is empty. 12 type Deque[T any] struct { 13 collection cols.Collection[T] 14 } 15 16 // NewArrayDeque creates a new Deque backed by an array. 17 func NewArrayDeque[T any]() Deque[T] { 18 return Deque[T]{array.New[T]()} 19 } 20 21 // NewLinkedListDeque creates a new Deque backed by a linked list. 22 func NewLinkedListDeque[T any]() Deque[T] { 23 return Deque[T]{linklist.New[T]()} 24 } 25 26 // From creates a new Deque from a collection. 27 func From[T any](collection cols.Collection[T]) Deque[T] { 28 return Deque[T]{collection} 29 } 30 31 // Empty returns true if the Deque is empty. 32 func (deque Deque[T]) Empty() bool { 33 return deque.collection.Size() == 0 34 } 35 36 // PushFront inserts an element at the front of the Deque. 37 func (deque Deque[T]) PushFront(value T) { 38 deque.collection.Insert(0, value) 39 } 40 41 // PushBack inserts an element at the back of the Deque. 42 func (deque Deque[T]) PushBack(value T) { 43 deque.collection.Append(value) 44 } 45 46 // PeekFront returns the element at the front of the Deque. 47 // Panics if the Deque is empty. 48 func (deque Deque[T]) PeekFront() T { 49 if deque.Empty() { 50 panic("Deque is empty") 51 } 52 53 return deque.collection.Get(0) 54 } 55 56 // PeekBack returns the element at the back of the Deque. 57 // Panics if the Deque is empty. 58 func (deque Deque[T]) PeekBack() T { 59 if deque.Empty() { 60 panic("Deque is empty") 61 } 62 63 return deque.collection.Get(-1) 64 } 65 66 // PopFront removes and returns the element at the front of the Deque. 67 // Panics if the Deque is empty. 68 func (deque Deque[T]) PopFront() T { 69 if deque.Empty() { 70 panic("Deque is empty") 71 } 72 73 defer deque.collection.Remove(0) 74 return deque.PeekFront() 75 } 76 77 // PopBack removes and returns the element at the back of the Deque. 78 // Panics if the Deque is empty. 79 func (deque Deque[T]) PopBack() T { 80 if deque.Empty() { 81 panic("Deque is empty") 82 } 83 84 defer deque.collection.Remove(-1) 85 return deque.PeekBack() 86 }