-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.go
52 lines (44 loc) · 1.35 KB
/
stack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Copyright 2022 Patrick Smith
// Use of this source code is subject to the MIT-style license in the LICENSE file.
// Package ds will implement some basic data structures in Go.
//
// For now, only Stack is provided.
package ds
// A Stack is a simple last-in-first-out collection of items.
type Stack[T any] struct {
items []T
}
// Push inserts a value into a Stack.
func (s *Stack[T]) Push(t T) {
s.items = append(s.items, t)
}
// Pop removes the value that was most recently inserted into a Stack, and not yet returned by Pop.
//
// It returns the value that was removed.
// Pop panics when called on an empty Stack.
func (s *Stack[T]) Pop() T {
l := len(s.items)
t := s.items[l-1]
s.items = s.items[:l-1]
return t
}
// Len returns the number of values currently in a Stack.
func (s Stack[T]) Len() int {
return len(s.items)
}
// Empty returns whether a Stack contains no values.
func (s Stack[T]) Empty() bool {
return len(s.items) == 0
}
// PushMany inserts several values into a stack.
//
// The values are inserted in the order given, so they will be returned by Pop in the reverse order.
func (s *Stack[T]) PushMany(ts ...T) {
s.items = append(s.items, ts...)
}
// Peek returns the same value as Pop, but does not remove it from the Stack.
//
// Peek panics when called on an empty Stack.
func (s *Stack[T]) Peek() T {
return s.items[len(s.items)-1]
}