diff --git a/LList.zig b/LList.zig index 09a3726..82c27df 100644 --- a/LList.zig +++ b/LList.zig @@ -1,19 +1,23 @@ const std = @import("std"); const Allocator = std.mem.Allocator; +const expect = std.testing.expect; +const testingAllocator = std.testing.allocator; + pub fn LList(comptime T: type) type { return struct { const Self = @This(); first: ?*Node(T), alloc: Allocator, + counter: u64, pub fn init(this: *Self, allocator: Allocator) !void { this.alloc = allocator; this.first = null; + this.counter = 0; } - pub fn deinit(this: *Self) !void { //? If there is no created Node @@ -25,6 +29,10 @@ pub fn LList(comptime T: type) type { var currentNode: *Node(T) = this.first orelse unreachable; while (true) { + if (currentNode.next == null){ + break; + } + const nextNode = currentNode.next orelse unreachable; var breakNext = false; @@ -41,6 +49,7 @@ pub fn LList(comptime T: type) type { } } try currentNode.deinit(); + this.counter = 0; } @@ -50,30 +59,16 @@ pub fn LList(comptime T: type) type { try newNode.init(this.alloc, value, this.first); this.first = newNode; + this.counter = this.counter + 1; + return newNode; } + pub fn size(this: *Self) !u64{ - pub fn printList(this: *Self) !void { - const writer = std.io.getStdOut().writer(); - - if (this.first == null) { - try writer.print("List is empty \n", .{}); - return; - } - - var currentNode: *Node(T) = this.first orelse unreachable; - - while (true) { - try writer.print("{any}\n", .{currentNode.value.*}); - currentNode = currentNode.next orelse unreachable; - - if (currentNode.next == null) { - break; - } - } - try writer.print("{any}\n", .{currentNode.value.*}); + return this.counter; } + }; } @@ -82,7 +77,7 @@ pub fn Node(comptime T: type) type { return struct { const Self = @This(); alloc: Allocator, - next: ?*Self, //? Nächste Node in der Liste + next: ?*Self, value: *T, pub fn init(this: *Self, allocator: Allocator, value: T, next: ?*Self) !void { @@ -100,25 +95,35 @@ pub fn Node(comptime T: type) type { } - pub fn printNode(this: *Self) !void { - const writer = std.io.getStdOut().writer(); - try writer.print("Value: {any} \n", .{this.value}); - } }; } -pub fn main() !void { - var gpa = std.heap.GeneralPurposeAllocator(.{}){}; - const allocator = gpa.allocator(); +test "leaks" { var testList: LList(u64) = undefined; - try testList.init(allocator); + try testList.init(testingAllocator); + + _ = try testList.add(1); + _ = try testList.add(2); + + + try testList.deinit(); + +} + + +test "size" { + + var testList: LList(u64) = undefined; + try testList.init(testingAllocator); + _ = try testList.add(1); _ = try testList.add(2); _ = try testList.add(3); _ = try testList.add(4); - try testList.printList(); + try expect(try testList.size() == 4); try testList.deinit(); + }