Question:
How does one iterate a (single) linked list structure and print the data of its members, when the members are linked through optional pointers like below?
Context:
Newbie to Zig here, I am trying to implement a member function which prints a single linked list by iterating over its elements.
I have the following structs, where Bord is a “list” of multiple Vakje structs:
pub const Vakje = struct {
next: ?*Vakje = null,
data: u8 = 0,
pub fn addNext(vak: *Vakje, new: *Vakje) void {
if (vak.next == null) {
vak.next = new;
std.debug.print("{s}\n", .{"added next!"});
}
}
};
pub const Bord = struct {
name: []const u8 = undefined,
first: ?*Vakje = null,
}
Most member functions are left out. I then tried to iterate over a Bord struct’s internal Vakje structs in some ways, which seems to not work properly (code most likely not useful for reader, can provide if wanted).
I have tried to adapt the linked list code from the zig std library to no avail;
https://github.com/ziglang/zig/blob/f9f894200891c8af6ce3a3ad222cd0bf1ee15587/lib/std/linked_list.zig#L56
/// Iterate over each next node, returning the count of all nodes except the starting one.
/// This operation is O(N).
pub fn countChildren(node: *const Node) usize {
var count: usize = 0;
var it: ?*const Node = node.next;
while (it) |n| : (it = n.next) {
count += 1;
}
return count;
}
I think this is due to a lack of understanding how optional pointers work. Unfortunately I have not been able to find an example, and something along the lines of https://ziggit.dev/t/iterating-optional-error-unions-i-e-t/5217
is above my current level of understanding, and does not seem to be the same question.
Question:
How does one iterate a (single) linked list structure and print the data of its members, when the members are linked through optional pointers like above?