feat(list_invert): SinglyLinkedList inversion.

This commit is contained in:
pseudoc
2023-07-13 01:22:18 +08:00
committed by Veikka Tuominen
parent 711b4e93e2
commit d78517f4f0

View File

@@ -61,6 +61,20 @@ pub fn SinglyLinkedList(comptime T: type) type {
}
return count;
}
/// Invert the list starting from this node in-place.
/// This operation is O(N).
pub fn invert(indirect: *?*Node) void {
if (indirect.* == null) {
return;
}
var current: *Node = indirect.*.?;
while (current.next) |next| {
current.next = next.next;
next.next = indirect.*;
indirect.* = next;
}
}
};
first: ?*Node = null,
@@ -149,6 +163,12 @@ test "basic SinglyLinkedList test" {
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.invert(&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);
}
/// A tail queue is headed by a pair of pointers, one to the head of the