I am confused as to how to use std.SinglyLinkedList and I’d like a couple of examples. I’m not familiar with the standard library, so excuse me if this is a stupid question.
I’m using zig 0.14.0-dev, in case that’s importent.
Edit: I have search for examples on google, but was not able to find any. which is why I’m asking here.
When You don’t know how to use something the best advice I can get is to look at the test in the standard library implementation to figure it out : For example for the SinglyLinkedList this is one basic test inside the file
test "basic SinglyLinkedList test" {
const L = SinglyLinkedList(u32);
var list = L{};
try testing.expect(list.len() == 0);
var one = L.Node{ .data = 1 };
var two = L.Node{ .data = 2 };
var three = L.Node{ .data = 3 };
var four = L.Node{ .data = 4 };
var five = L.Node{ .data = 5 };
list.prepend(&two); // {2}
two.insertAfter(&five); // {2, 5}
list.prepend(&one); // {1, 2, 5}
two.insertAfter(&three); // {1, 2, 3, 5}
three.insertAfter(&four); // {1, 2, 3, 4, 5}
try testing.expect(list.len() == 5);
// Traverse forwards.
{
var it = list.first;
var index: u32 = 1;
while (it) |node| : (it = node.next) {
try testing.expect(node.data == index);
index += 1;
}
}
_ = list.popFirst(); // {2, 3, 4, 5}
_ = list.remove(&five); // {2, 3, 4}
_ = two.removeNext(); // {2, 4}
try testing.expect(list.first.?.data == 2);
try testing.expect(list.first.?.next.?.data == 4);
try testing.expect(list.first.?.next.?.next == null);
L.Node.reverse(&list.first);
try testing.expect(list.first.?.data == 4);
try testing.expect(list.first.?.next.?.data == 2);
try testing.expect(list.first.?.next.?.next == null);
}
As a general rule of thumb when I’m not sure how to use something from the STD the tests are my goto to understand it better.
But If you want I also have my own implementation that I made that was more inline with the kind of list I was using in C. Because I was also confused with the one in the STD