1 | module datatypes |
2 | |
3 | pub struct Stack[T] { |
4 | mut: |
5 | elements []T |
6 | } |
7 | |
8 | // is_empty checks if the stack is empty |
9 | pub fn (stack Stack[T]) is_empty() bool { |
10 | return stack.elements.len == 0 |
11 | } |
12 | |
13 | // len returns the length of the stack |
14 | pub fn (stack Stack[T]) len() int { |
15 | return stack.elements.len |
16 | } |
17 | |
18 | // peek returns the top of the stack |
19 | pub 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 |
24 | pub 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 |
29 | pub 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 |
34 | pub fn (stack Stack[T]) str() string { |
35 | return stack.elements.str() |
36 | } |
37 | |
38 | // array returns a array representation of the stack |
39 | pub fn (stack Stack[T]) array() []T { |
40 | return stack.elements |
41 | } |