Commit fc3508b7e8

J.C. Moyer <jcmoyer32@gmail.com>
2021-01-04 15:15:39
Fix off-by-one error in SinglyLinkedList.len() and add associated tests
1 parent a93c123
Changed files (1)
lib/std/linked_list.zig
@@ -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;