| ... | @@ -61,6 +61,20 @@ pub fn SinglyLinkedList(comptime T: type) type { | ... | @@ -61,6 +61,20 @@ pub fn SinglyLinkedList(comptime T: type) type { |
| 61 | } | 61 | } |
| 62 | return count; | 62 | return count; |
| 63 | } | 63 | } |
| | 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 | } |
| 64 | }; | 78 | }; |
| 65 | | 79 | |
| 66 | first: ?*Node = null, | 80 | first: ?*Node = null, |
| ... | @@ -149,6 +163,12 @@ test "basic SinglyLinkedList test" { | ... | @@ -149,6 +163,12 @@ test "basic SinglyLinkedList test" { |
| 149 | try testing.expect(list.first.?.data == 2); | 163 | try testing.expect(list.first.?.data == 2); |
| 150 | try testing.expect(list.first.?.next.?.data == 4); | 164 | try testing.expect(list.first.?.next.?.data == 4); |
| 151 | try testing.expect(list.first.?.next.?.next == null); | 165 | 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); |
| 152 | } | 172 | } |
| 153 | | 173 | |
| 154 | /// A tail queue is headed by a pair of pointers, one to the head of the | 174 | /// A tail queue is headed by a pair of pointers, one to the head of the |