Created
September 6, 2022 12:10
-
-
Save RaphGL/8c269d15b10c2cfec83b14229e2db74d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const allocator = std.heap.page_allocator; | |
pub fn LinkedList(comptime T: type) type { | |
return struct { | |
const AllocatorError = std.mem.Allocator.Error; | |
const Self = @This(); | |
data: T, | |
next: ?*Self = null, | |
const LlsError = error{ CouldNotPop }; | |
pub fn create(val: T) AllocatorError!*Self { | |
var node = try allocator.create(Self); | |
node.* = .{ .data = val }; | |
return node; | |
} | |
pub fn push(self: *Self, val: T) AllocatorError!void { | |
var tmp = self; | |
while (tmp.next) |next| { | |
tmp = next; | |
} | |
var node = try create(val); | |
tmp.next = node; | |
} | |
pub fn pop(self: *Self) LlsError!T { | |
var tmp = self; | |
if (tmp.next == null) { | |
defer allocator.destroy(tmp); | |
return tmp.data; | |
} | |
var next_tmp = self.next orelse return LlsError.CouldNotPop; | |
while (next_tmp.next) |next| { | |
next_tmp = next; | |
tmp = tmp.next.?; | |
} | |
defer allocator.destroy(next_tmp); | |
tmp.next = null; | |
return next_tmp.data; | |
} | |
pub fn print(self: *Self) std.os.WriteError!void { | |
var tmp = self; | |
const stdout = std.io.getStdIn().writer(); | |
try stdout.print("[", .{}); | |
while (true) { | |
try stdout.print(" {}", .{tmp.data}); | |
tmp = tmp.next orelse break; | |
} | |
try stdout.print(" ]\n", .{}); | |
} | |
}; | |
} | |
pub fn main() !void { | |
var lls = try LinkedList(u32).create(1); | |
try lls.push(2); | |
try lls.push(3); | |
try lls.print(); | |
var val = try lls.pop(); | |
std.debug.print("val: {}", .{val}); | |
try lls.print(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment