v / vlib / datatypes
Raw file | 41 loc (33 sloc) | 1001 bytes | Latest commit hash 7d8c38672
1module datatypes
2
3pub struct Stack[T] {
4mut:
5 elements []T
6}
7
8// is_empty checks if the stack is empty
9pub fn (stack Stack[T]) is_empty() bool {
10 return stack.elements.len == 0
11}
12
13// len returns the length of the stack
14pub fn (stack Stack[T]) len() int {
15 return stack.elements.len
16}
17
18// peek returns the top of the stack
19pub fn (stack Stack[T]) peek() !T {
20 return if !stack.is_empty() { stack.elements.last() } else { error('Stack is empty') }
21}
22
23// push adds an element to the top of the stack
24pub fn (mut stack Stack[T]) push(item T) {
25 stack.elements << item
26}
27
28// pop removes the element at the top of the stack and returns it
29pub fn (mut stack Stack[T]) pop() !T {
30 return if !stack.is_empty() { stack.elements.pop() } else { error('Stack is empty') }
31}
32
33// str returns a string representation of the stack
34pub fn (stack Stack[T]) str() string {
35 return stack.elements.str()
36}
37
38// array returns a array representation of the stack
39pub fn (stack Stack[T]) array() []T {
40 return stack.elements
41}