authorgravatar for atlas.yu@canonical.compseudoc <atlas.yu@canonical.com> 2023-07-13 01:22:18+08:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2023-07-13 00:56:28+03:00
logd78517f4f0f540f0d0254a78e47a7b4a30e98c74
treeeb54a4be3a07e8761abd6320c680afe02efc023f
parent711b4e93e2b98233a5e225611891a0c25c6c12d9

feat(list_invert): SinglyLinkedList inversion.


1 files changed, 20 insertions(+), 0 deletions(-)

lib/std/linked_list.zig+20
......@@ -61,6 +61,20 @@ pub fn SinglyLinkedList(comptime T: type) type {
6161 }
6262 return count;
6363 }
64
65 /// Invert the list starting from this node in-place.
66 /// This operation is O(N).
67 pub fn invert(indirect: *?*Node) void {
68 if (indirect.* == null) {
69 return;
70 }
71 var current: *Node = indirect.*.?;
72 while (current.next) |next| {
73 current.next = next.next;
74 next.next = indirect.*;
75 indirect.* = next;
76 }
77 }
6478 };
6579
6680 first: ?*Node = null,
......@@ -149,6 +163,12 @@ test "basic SinglyLinkedList test" {
149163 try testing.expect(list.first.?.data == 2);
150164 try testing.expect(list.first.?.next.?.data == 4);
151165 try testing.expect(list.first.?.next.?.next == null);
166
167 L.Node.invert(&list.first);
168
169 try testing.expect(list.first.?.data == 4);
170 try testing.expect(list.first.?.next.?.data == 2);
171 try testing.expect(list.first.?.next.?.next == null);
152172}
153173
154174/// A tail queue is headed by a pair of pointers, one to the head of the