Skip to content

Commit fc3508b

Browse files
jcmoyerandrewrk
authored andcommitted
Fix off-by-one error in SinglyLinkedList.len() and add associated tests
1 parent a93c123 commit fc3508b

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

lib/std/linked_list.zig

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ pub fn SinglyLinkedList(comptime T: type) type {
6262
/// This operation is O(N).
6363
pub fn countChildren(node: *const Node) usize {
6464
var count: usize = 0;
65-
var it: ?*const Node = node;
65+
var it: ?*const Node = node.next;
6666
while (it) |n| : (it = n.next) {
6767
count += 1;
6868
}
@@ -123,6 +123,8 @@ test "basic SinglyLinkedList test" {
123123
const L = SinglyLinkedList(u32);
124124
var list = L{};
125125

126+
testing.expect(list.len() == 0);
127+
126128
var one = L.Node{ .data = 1 };
127129
var two = L.Node{ .data = 2 };
128130
var three = L.Node{ .data = 3 };
@@ -135,6 +137,8 @@ test "basic SinglyLinkedList test" {
135137
two.insertAfter(&three); // {1, 2, 3, 5}
136138
three.insertAfter(&four); // {1, 2, 3, 4, 5}
137139

140+
testing.expect(list.len() == 5);
141+
138142
// Traverse forwards.
139143
{
140144
var it = list.first;

0 commit comments

Comments
 (0)