diff options
| author | Zuhaitz <zuhaitz.zechhub@gmail.com> | 2026-01-20 18:50:20 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-01-20 18:50:20 +0000 |
| commit | c52637a16cfb1d94458453d3b4d11a80db191f2d (patch) | |
| tree | 50cac4e039b312be91af80c2092fbc2361e2b49d /std/stack.zc | |
| parent | 6165c437410052fa177fc1245c176ec6709a9da7 (diff) | |
| parent | 14463b3961c03eac5c4f2fa493a354bc866bf6c2 (diff) | |
Merge pull request #82 from lamweilun/dev/weilun/stack_and_queue
Stack and Queue implementation, with unit tests
Diffstat (limited to 'std/stack.zc')
| -rw-r--r-- | std/stack.zc | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/std/stack.zc b/std/stack.zc new file mode 100644 index 0000000..3d7c3c5 --- /dev/null +++ b/std/stack.zc @@ -0,0 +1,59 @@ +import "./option.zc" +import "./mem.zc" + +struct Stack<T> { + data: T*; + len: usize; + cap: usize; +} + +impl Stack<T> { + fn new() -> Stack<T> { + return Stack<T>{data: NULL, len: 0, cap: 0}; + } + + fn free(self) { + if (self.data) { + free(self.data); + self.data = NULL; + } + self.len = 0; + } + + fn clone(self) -> Stack<T> { + var new_stack = Stack<T>::new(); + new_stack.len = self.len; + new_stack.cap = self.cap; + new_stack.data = malloc(sizeof(T) * new_stack.cap); + memcpy(new_stack.data, self.data, sizeof(T) * new_stack.cap); + return new_stack; + } + + fn push(self, value: T) { + if (!self.data) { + self.cap = 8; + self.data = malloc(sizeof(T) * self.cap); + } + if (self.len == self.cap) { + self.cap = self.cap * 2; + self.data = realloc(self.data, sizeof(T) * self.cap); + } + self.data[self.len] = value; + self.len = self.len + 1; + } + + fn pop(self) -> Option<T> { + if (self.len > 0) { + var value = self.data[self.len - 1]; + self.len = self.len - 1; + return Option<T>::Some(value); + } + return Option<T>::None(); + } +} + +impl Drop for Stack<T> { + fn drop(self) { + self.free(); + } +} |
