Stack and Queue
import "std/collections" (included in import "std") · namespace std.collections
Stack<T>is last in, first out:pushputs an element on top,poptakes the top one. Think of a stack of plates, an undo history, or matching brackets.Queue<T>is first in, first out:enqueueadds at the back,dequeuetakes from the front. Think of a waiting line or a work queue.
Every operation is O(1). Taking from an empty stack or queue throws StateError; peekOr(fallback) never throws.
grav
import "std"
fn balanced(s: string) -> bool {
let open = new Stack<string>()
for (ch in s) {
if (ch == "(" || ch == "[") { open.push(ch) }
else if (ch == ")" || ch == "]") {
if (open.isEmpty()) { return false }
let top = open.pop()
if ((ch == ")" && top != "(") || (ch == "]" && top != "[")) { return false }
}
}
return open.isEmpty()
}
fn main() {
print(balanced("(a[b])"))
print(balanced("(a[b)]"))
let jobs = new Queue<string>()
jobs.enqueue("first")
jobs.enqueue("second")
print(jobs.dequeue())
print(jobs.peek())
print(jobs.size())
print(new Stack<int>().peekOr(-1))
}true
false
first
second
1
-1API
class Stack<T>
Constructors
new Stack()
Methods
fn push(item: T)— Puts an element on top.fn pop() -> T— Removes and returns the top element (StateError when empty).fn peek() -> T— The top element, left in place (StateError when empty).fn peekOr(fallback: T) -> T— The top element, orfallbackwhen empty.fn size() -> int— The number of elements.fn length() -> int— The number of elements (same as size()).fn isEmpty() -> bool— Whether the stack is empty.fn clear()— Removes every element.fn contains(item: T) -> bool— Whether some element equalsitem.fn get(i: int) -> T— Index 0 is the bottom of the stack.fn forEach(f: fn(T))— Calls f on each element, bottom first.fn toString() -> string— As text: [1, 2, 3] (strings in quotes).fn toArray() -> Array<T>— The elements as a new Array, bottom first.
class Queue<T>
Constructors
new Queue()
Methods
fn enqueue(item: T)— Adds an element at the back.fn dequeue() -> T— Removes and returns the front element (StateError when empty).fn peek() -> T— The front element, left in place (StateError when empty).fn peekOr(fallback: T) -> T— The front element, orfallbackwhen empty.fn size() -> int— The number of elements.fn length() -> int— The number of elements (same as size()).fn isEmpty() -> bool— Whether the queue is empty.fn clear()— Removes every element.fn contains(item: T) -> bool— Whether some element equalsitem.fn get(i: int) -> T— Index 0 is the front (next to dequeue).fn forEach(f: fn(T))— Calls f on each element, front first.fn toString() -> string— As text: [1, 2, 3] (strings in quotes).fn toArray() -> Array<T>— The elements as a new Array, front first.