PR3L-Verkettete-Listen-Abgabe2/LList.zig

60 lines
1.5 KiB
Zig

const std = @import("std");
const Allocator = std.mem.Allocator;
pub fn LList(comptime T: type) type {
return struct {
const Self = @This();
first: ?*Node(T),
alloc: Allocator,
pub fn init(this: *Self, allocator: Allocator) !void {
this.alloc = allocator;
this.first = try allocator.create(Node(T));
}
pub fn deinit(this: *Self) void {
//TODO
this.alloc.destroy(T); //? Muss in einer Schleife durchlaufen
}
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 Node(comptime T: type) type {
return struct {
const Self = @This();
next: ?*Self, //? Nächste Node in der Liste
value: T,
pub fn init(this: *Self, value: T, next: ?*Self) void {
this.value = value;
this.next = next;
}
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();
var testList: LList(u64) = undefined;
try testList.init(allocator);
}