summaryrefslogtreecommitdiff
path: root/examples/data_structures/linked_list.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/linked_list.zc
parentff32e7b6b99dd9b17b4c581e6c48308128f46c52 (diff)
A few examples, some more will be added soon.
Diffstat (limited to 'examples/data_structures/linked_list.zc')
-rw-r--r--examples/data_structures/linked_list.zc85
1 files changed, 85 insertions, 0 deletions
diff --git a/examples/data_structures/linked_list.zc b/examples/data_structures/linked_list.zc
new file mode 100644
index 0000000..cb85554
--- /dev/null
+++ b/examples/data_structures/linked_list.zc
@@ -0,0 +1,85 @@
+
+import "std/mem.zc"
+
+struct Node {
+ value: int;
+ next: Node*;
+}
+
+impl Node {
+ fn new(v: int) -> Self* {
+ var n = alloc<Node>();
+ guard n != NULL else {
+ "Out of memory!";
+ return NULL;
+ }
+ n.value = v;
+ n.next = NULL;
+ return n;
+ }
+}
+
+struct LinkedList {
+ head: Node*;
+}
+
+impl LinkedList {
+ fn new() -> Self {
+ return Self { head: NULL };
+ }
+
+ fn push(self, v: int) {
+ var new_node = Node::new(v);
+ guard new_node != NULL else { return; }
+
+ new_node.next = self.head;
+ self.head = new_node;
+ }
+
+ fn print_list(self) {
+ var current: Node* = self.head;
+ "["..;
+ while current != NULL {
+ "{current.value}"..;
+ current = current.next;
+ if current != NULL {
+ " -> "..;
+ }
+ }
+ "]";
+ }
+
+ fn free(self) {
+ var current: Node* = self.head;
+ while current != NULL {
+ autofree var temp = current;
+ current = current.next;
+ }
+ self.head = NULL;
+ }
+
+ fn len(self) -> int {
+ var count = 0;
+ var current: Node* = self.head;
+ while current != NULL {
+ count++;
+ current = current.next;
+ }
+ return count;
+ }
+}
+
+fn main() {
+ var list = LinkedList::new();
+ defer list.free();
+
+ "Pushing: 10, 20, 30...";
+ list.push(10);
+ list.push(20);
+ list.push(30);
+
+ "List length: {list.len()}";
+
+ "Current List: "..;
+ list.print_list();
+}