Fix off-by-one error in SinglyLinkedList.len() and add associated tests

This commit is contained in:
J.C. Moyer 2021-01-04 09:15:39 -05:00 committed by Andrew Kelley
parent a93c123f83
commit fc3508b7e8

View File

@ -62,7 +62,7 @@ pub fn SinglyLinkedList(comptime T: type) type {
/// This operation is O(N).
pub fn countChildren(node: *const Node) usize {
var count: usize = 0;
var it: ?*const Node = node;
var it: ?*const Node = node.next;
while (it) |n| : (it = n.next) {
count += 1;
}
@ -123,6 +123,8 @@ test "basic SinglyLinkedList test" {
const L = SinglyLinkedList(u32);
var list = L{};
testing.expect(list.len() == 0);
var one = L.Node{ .data = 1 };
var two = L.Node{ .data = 2 };
var three = L.Node{ .data = 3 };
@ -135,6 +137,8 @@ test "basic SinglyLinkedList test" {
two.insertAfter(&three); // {1, 2, 3, 5}
three.insertAfter(&four); // {1, 2, 3, 4, 5}
testing.expect(list.len() == 5);
// Traverse forwards.
{
var it = list.first;