diff --git a/LList.zig b/LList.zig index 78a99e8..09a3726 100644 --- a/LList.zig +++ b/LList.zig @@ -7,41 +7,99 @@ pub fn LList(comptime T: type) type { first: ?*Node(T), alloc: Allocator, + pub fn init(this: *Self, allocator: Allocator) !void { this.alloc = allocator; - this.first = try allocator.create(Node(T)); + this.first = null; } - pub fn deinit(this: *Self) void { - //TODO - this.alloc.destroy(T); //? Muss in einer Schleife durchlaufen + + pub fn deinit(this: *Self) !void { + + //? If there is no created Node + if (this.first == null) { + //? Nothing to do + return; + } + + var currentNode: *Node(T) = this.first orelse unreachable; + + while (true) { + const nextNode = currentNode.next orelse unreachable; + var breakNext = false; + + if (nextNode.next == null) { + breakNext = true; + } + + try currentNode.deinit(); + + currentNode = nextNode; + + if (breakNext == true) { + break; + } + } + try currentNode.deinit(); } - pub fn add(this: *Self, value: T ) *type{ - const newFirst = try this.alloc.create(Node(T)); - var node: Node(T) = undefined; - this.first.* = try node.init(value, this.first); - - this.first = newFirst; - return this.first; + pub fn add(this: *Self, value: T ) !*Node(T){ + + const newNode: *Node(T) = try this.alloc.create(Node(T)); + try newNode.init(this.alloc, value, this.first); + this.first = newNode; + + return newNode; + } + 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.*}); } }; } + pub fn Node(comptime T: type) type { return struct { const Self = @This(); + alloc: Allocator, next: ?*Self, //? Nächste Node in der Liste - value: T, + value: *T, - pub fn init(this: *Self, value: T, next: ?*Self) void { - this.value = value; + pub fn init(this: *Self, allocator: Allocator, value: T, next: ?*Self) !void { + this.alloc = allocator; this.next = next; + + this.value = try this.alloc.create(T); + this.value.* = value; } + + pub fn deinit(this: *Self) !void { + this.alloc.destroy(this.value); + this.alloc.destroy(this); + } + + pub fn printNode(this: *Self) !void { const writer = std.io.getStdOut().writer(); try writer.print("Value: {any} \n", .{this.value}); @@ -55,5 +113,12 @@ pub fn main() !void { var testList: LList(u64) = undefined; try testList.init(allocator); + _ = try testList.add(1); + _ = try testList.add(2); + _ = try testList.add(3); + _ = try testList.add(4); + try testList.printList(); + + try testList.deinit(); }