Created
July 26, 2025 15:20
-
-
Save doccaico/9b692c4b65bf4d7878d29964cdd13cf8 to your computer and use it in GitHub Desktop.
SinglyLinedList in Zig
This file contains hidden or 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 fmt = std.fmt; | |
const mem = std.mem; | |
const print = std.debug.print; | |
const assert = std.debug.assert; | |
const expect = std.testing.expect; | |
const Allocator = mem.Allocator; | |
// zig run singly_linked_list.zig | |
// zig test singly_linked_list.zig | |
// SinglyLinedList in heap | |
fn SinglyLinedList(comptime T: type) type { | |
return struct { | |
const Self = @This(); | |
first: ?*Node, | |
allocator: Allocator, | |
pub const Node = struct { | |
next: ?*Node, | |
data: T, | |
}; | |
fn init(allocator: Allocator) Self { | |
return Self{ | |
.first = null, | |
.allocator = allocator, | |
}; | |
} | |
fn deinit(self: Self) void { | |
var it = self.first; | |
while (it) |node| { | |
it = node.next; | |
self.allocator.destroy(node); | |
} | |
} | |
fn prepend(self: *Self, data: T) Allocator.Error!void { | |
var new_node = try self.allocator.create(Node); | |
new_node.data = data; | |
const temp = self.first; | |
self.first = new_node; | |
self.first.?.next = temp; | |
} | |
fn append(self: *Self, data: T) Allocator.Error!void { | |
var new_node = try self.allocator.create(Node); | |
new_node.data = data; | |
new_node.next = null; | |
if (self.first) |n1| { | |
var it = n1; | |
while (it.next) |n2| { | |
it = n2; | |
} | |
it.next = new_node; | |
} else { | |
self.first = new_node; | |
} | |
} | |
}; | |
} | |
test "init" { | |
var list = SinglyLinedList(i32).init(std.testing.allocator); | |
defer list.deinit(); | |
try expect(list.first == null); | |
} | |
test "prepend" { | |
var list = SinglyLinedList(i32).init(std.testing.allocator); | |
defer list.deinit(); | |
try list.prepend(1); | |
try list.prepend(2); | |
try list.prepend(3); | |
try expect(list.first.?.data == 3); | |
try expect(list.first.?.next.?.data == 2); | |
try expect(list.first.?.next.?.next.?.data == 1); | |
try expect(list.first.?.next.?.next.?.next == null); | |
} | |
test "append" { | |
var list = SinglyLinedList(i32).init(std.testing.allocator); | |
defer list.deinit(); | |
try list.append(1); | |
try list.append(2); | |
try list.append(3); | |
try expect(list.first.?.data == 1); | |
try expect(list.first.?.next.?.data == 2); | |
try expect(list.first.?.next.?.next.?.data == 3); | |
try expect(list.first.?.next.?.next.?.next == null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment