Complete project3
This commit is contained in:
27
stack_ds/src/main.zig
Normal file
27
stack_ds/src/main.zig
Normal file
@@ -0,0 +1,27 @@
|
||||
const std = @import("std");
|
||||
const Stack = @import("stack.zig").Stack;
|
||||
|
||||
pub fn main() !void {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
const allocator = gpa.allocator();
|
||||
const Stacku8 = Stack(u8);
|
||||
|
||||
var stack: Stacku8 = try Stacku8.init(allocator, 100);
|
||||
defer stack.deinit();
|
||||
|
||||
try stack.push(10);
|
||||
try stack.push(20);
|
||||
try stack.push(30);
|
||||
try stack.push(40);
|
||||
try stack.push(50);
|
||||
try stack.push(60);
|
||||
|
||||
std.debug.print("Stack length: {d}\n", .{stack.length});
|
||||
std.debug.print("Stack capacity: {d}\n", .{stack.capacity});
|
||||
|
||||
var popped = stack.pop();
|
||||
std.debug.print("Stack len: {d}. Popped value: {d}\n", .{stack.length, popped.?});
|
||||
popped = stack.pop();
|
||||
std.debug.print("Stack len: {d}. Popped value: {d}\n", .{stack.length, popped.?});
|
||||
std.debug.print("Stack state: {any}\n", .{stack.items[0..stack.length]});
|
||||
}
|
||||
56
stack_ds/src/stack.zig
Normal file
56
stack_ds/src/stack.zig
Normal file
@@ -0,0 +1,56 @@
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub fn Stack(comptime T: type) type {
|
||||
return struct {
|
||||
items: []T,
|
||||
capacity: usize,
|
||||
length: usize,
|
||||
allocator: Allocator,
|
||||
const Self = @This();
|
||||
|
||||
pub fn init(allocator: Allocator, capacity: usize) !Stack(T) {
|
||||
var buf = try allocator.alloc(T, capacity);
|
||||
|
||||
return .{
|
||||
.items = buf[0..],
|
||||
.capacity = capacity,
|
||||
.length = 0,
|
||||
.allocator = allocator,
|
||||
};
|
||||
}
|
||||
|
||||
pub fn push(self: *Self, item: T) !void {
|
||||
if (self.length == self.capacity) {
|
||||
const new_capacity: usize = self.capacity * 2;
|
||||
var new_buf = try self.allocator.alloc(T, new_capacity);
|
||||
@memcpy(new_buf[0..self.capacity], self.items);
|
||||
self.allocator.free(self.items);
|
||||
self.items = new_buf;
|
||||
self.capacity = new_capacity;
|
||||
}
|
||||
|
||||
self.items[self.length] = item;
|
||||
self.length += 1;
|
||||
}
|
||||
|
||||
pub fn pop(self: *Self) ?T {
|
||||
if (self.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const index: usize = self.length - 1;
|
||||
const out = self.items[index];
|
||||
self.items[index] = undefined;
|
||||
self.length -= 1;
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
pub fn deinit(self: *Self) void {
|
||||
self.allocator.free(self.items);
|
||||
self.capacity = 0;
|
||||
self.length = 0;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user