Skip to content

Commit

Permalink
Fix off-by-one error in SinglyLinkedList.len() and add associated tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jcmoyer authored and andrewrk committed Jan 4, 2021
1 parent a93c123 commit fc3508b
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/std/linked_list.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 };
Expand All @@ -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;
Expand Down

0 comments on commit fc3508b

Please sign in to comment.