2021-12-26 17:01:36 +03:00
|
|
|
module datatypes
|
2021-12-23 16:16:29 +03:00
|
|
|
|
2022-11-26 19:23:26 +03:00
|
|
|
pub struct Stack[T] {
|
2021-12-23 16:16:29 +03:00
|
|
|
mut:
|
|
|
|
elements []T
|
|
|
|
}
|
|
|
|
|
|
|
|
// is_empty checks if the stack is empty
|
2022-11-26 19:23:26 +03:00
|
|
|
pub fn (stack Stack[T]) is_empty() bool {
|
2021-12-23 16:16:29 +03:00
|
|
|
return stack.elements.len == 0
|
|
|
|
}
|
|
|
|
|
|
|
|
// len returns the length of the stack
|
2022-11-26 19:23:26 +03:00
|
|
|
pub fn (stack Stack[T]) len() int {
|
2021-12-23 16:16:29 +03:00
|
|
|
return stack.elements.len
|
|
|
|
}
|
|
|
|
|
|
|
|
// peek returns the top of the stack
|
2022-11-28 11:24:47 +03:00
|
|
|
pub fn (stack Stack[T]) peek() !T {
|
2021-12-23 16:16:29 +03:00
|
|
|
return if !stack.is_empty() { stack.elements.last() } else { error('Stack is empty') }
|
|
|
|
}
|
|
|
|
|
|
|
|
// push adds an element to the top of the stack
|
2022-11-26 19:23:26 +03:00
|
|
|
pub fn (mut stack Stack[T]) push(item T) {
|
2021-12-23 16:16:29 +03:00
|
|
|
stack.elements << item
|
|
|
|
}
|
|
|
|
|
|
|
|
// pop removes the element at the top of the stack and returns it
|
2022-11-28 11:24:47 +03:00
|
|
|
pub fn (mut stack Stack[T]) pop() !T {
|
2021-12-23 16:16:29 +03:00
|
|
|
return if !stack.is_empty() { stack.elements.pop() } else { error('Stack is empty') }
|
|
|
|
}
|
|
|
|
|
|
|
|
// str returns a string representation of the stack
|
2022-11-26 19:23:26 +03:00
|
|
|
pub fn (stack Stack[T]) str() string {
|
2021-12-23 16:16:29 +03:00
|
|
|
return stack.elements.str()
|
|
|
|
}
|
2022-08-25 14:12:39 +03:00
|
|
|
|
|
|
|
// array returns a array representation of the stack
|
2022-11-26 19:23:26 +03:00
|
|
|
pub fn (stack Stack[T]) array() []T {
|
2022-08-25 14:12:39 +03:00
|
|
|
return stack.elements
|
|
|
|
}
|