summaryrefslogtreecommitdiff
path: root/examples/data_structures/stack.zc
diff options
context:
space:
mode:
authorZuhaitz Méndez Fernández de Aránguiz <zuhaitz@debian>2026-01-11 21:13:29 +0000
committerZuhaitz Méndez Fernández de Aránguiz <zuhaitz@debian>2026-01-11 21:13:50 +0000
commit36938b584ea2d096d97a124b70da51f685850ff7 (patch)
tree768c132d8a661c74f36683005548cf6afb163714 /examples/data_structures/stack.zc
parentff32e7b6b99dd9b17b4c581e6c48308128f46c52 (diff)
A few examples, some more will be added soon.
Diffstat (limited to 'examples/data_structures/stack.zc')
-rw-r--r--examples/data_structures/stack.zc81
1 files changed, 81 insertions, 0 deletions
diff --git a/examples/data_structures/stack.zc b/examples/data_structures/stack.zc
new file mode 100644
index 0000000..8f1fea5
--- /dev/null
+++ b/examples/data_structures/stack.zc
@@ -0,0 +1,81 @@
+
+import "std.zc"
+
+struct Stack<T> {
+ data: Vec<T>;
+}
+
+impl Stack<T> {
+ fn new() -> Self {
+ return Self { data: Vec<T>::new() };
+ }
+
+ fn push(self, item: T) {
+ self.data.push(item);
+ }
+
+ fn pop(self) -> Option<T> {
+ if self.data.length() == 0 {
+ return Option<T>::None();
+ }
+ return Option<T>::Some(self.data.pop());
+ }
+
+ fn peek(self) -> Option<T> {
+ if self.data.length() == 0 {
+ return Option<T>::None();
+ }
+ return Option<T>::Some(self.data.last());
+ }
+
+ fn is_empty(self) -> bool {
+ return self.data.length() == 0;
+ }
+
+ fn size(self) -> usize {
+ return self.data.length();
+ }
+
+ fn free(self) {
+ self.data.free();
+ }
+}
+
+fn main() {
+ "[Integer Stack]";
+ var int_stack = Stack<int>::new();
+ defer int_stack.free();
+
+ "Pushing: 10, 20, 30";
+ int_stack.push(10);
+ int_stack.push(20);
+ int_stack.push(30);
+
+ "Size: {int_stack.size()}";
+ var p = int_stack.peek();
+ "Peek: {p.unwrap()}";
+
+ "Popping: "..;
+ while !int_stack.is_empty() {
+ var opt = int_stack.pop();
+ "{opt.unwrap()} "..;
+ }
+ "";
+
+ "";
+ "[String Stack]";
+ var str_stack = Stack<String>::new();
+ defer str_stack.free();
+
+ str_stack.push(String::new("First"));
+ str_stack.push(String::new("Second"));
+ str_stack.push(String::new("Third"));
+
+ "Popping: "..;
+ while !str_stack.is_empty() {
+ var opt_s = str_stack.pop();
+ var s: String = opt_s.unwrap();
+ "{s.c_str()} "..;
+ }
+ "";
+}