feat(list_invert): SinglyLinkedList inversion.
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user