This commit is contained in:
krahets
2025-09-11 03:53:49 +08:00
parent 3f088184e4
commit ae2e2535f4
24 changed files with 456 additions and 380 deletions
+22 -12
View File
@@ -21,7 +21,7 @@ comments: true
```python title="array.py"
# 初始化数组
arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ]
nums: list[int] = [1, 3, 2, 5, 4]
nums: list[int] = [1, 3, 2, 5, 4]
```
=== "C++"
@@ -136,8 +136,8 @@ comments: true
```zig title="array.zig"
// 初始化数组
var arr = [_]i32{0} ** 5; // { 0, 0, 0, 0, 0 }
var nums = [_]i32{ 1, 3, 2, 5, 4 };
const arr = [_]i32{0} ** 5; // { 0, 0, 0, 0, 0 }
const nums = [_]i32{ 1, 3, 2, 5, 4 };
```
??? pythontutor "可视化运行"
@@ -330,11 +330,11 @@ comments: true
```zig title="array.zig"
// 随机访问元素
fn randomAccess(nums: []i32) i32 {
fn randomAccess(nums: []const i32) i32 {
// 在区间 [0, nums.len) 中随机抽取一个整数
var randomIndex = std.crypto.random.intRangeLessThan(usize, 0, nums.len);
const random_index = std.crypto.random.intRangeLessThan(usize, 0, nums.len);
// 获取并返回随机元素
var randomNum = nums[randomIndex];
const randomNum = nums[random_index];
return randomNum;
}
```
@@ -984,18 +984,26 @@ comments: true
```zig title="array.zig"
// 遍历数组
fn traverse(nums: []i32) void {
fn traverse(nums: []const i32) void {
var count: i32 = 0;
// 通过索引遍历数组
var i: i32 = 0;
var i: usize = 0;
while (i < nums.len) : (i += 1) {
count += nums[i];
}
count = 0;
// 直接遍历数组元素
count = 0;
for (nums) |num| {
count += num;
}
// 同时遍历数据索引和元素
for (nums, 0..) |num, index| {
count += nums[index];
count += num;
}
}
```
@@ -1427,12 +1435,14 @@ comments: true
```zig title="array.zig"
// 扩展数组长度
fn extend(mem_allocator: std.mem.Allocator, nums: []i32, enlarge: usize) ![]i32 {
fn extend(allocator: std.mem.Allocator, nums: []const i32, enlarge: usize) ![]i32 {
// 初始化一个扩展长度后的数组
var res = try mem_allocator.alloc(i32, nums.len + enlarge);
const res = try allocator.alloc(i32, nums.len + enlarge);
@memset(res, 0);
// 将原数组中的所有元素复制到新数组
std.mem.copy(i32, res, nums);
std.mem.copyForwards(i32, res, nums);
// 返回扩展后的新数组
return res;
}
@@ -621,10 +621,10 @@ comments: true
```zig title="linked_list.zig"
// 在链表的节点 n0 之后插入节点 P
fn insert(n0: ?*inc.ListNode(i32), P: ?*inc.ListNode(i32)) void {
var n1 = n0.?.next;
P.?.next = n1;
n0.?.next = P;
fn insert(comptime T: type, n0: *ListNode(T), P: *ListNode(T)) void {
const n1 = n0.next;
P.next = n1;
n0.next = P;
}
```
@@ -835,12 +835,11 @@ comments: true
```zig title="linked_list.zig"
// 删除链表的节点 n0 之后的首个节点
fn remove(n0: ?*inc.ListNode(i32)) void {
if (n0.?.next == null) return;
// n0 -> P -> n1
var P = n0.?.next;
var n1 = P.?.next;
n0.?.next = n1;
fn remove(comptime T: type, n0: *ListNode(T)) void {
// n0 -> P -> n1 => n0 -> n1
const P = n0.next;
const n1 = P.?.next;
n0.next = n1;
}
```
@@ -1052,12 +1051,15 @@ comments: true
```zig title="linked_list.zig"
// 访问链表中索引为 index 的节点
fn access(node: ?*inc.ListNode(i32), index: i32) ?*inc.ListNode(i32) {
var head = node;
fn access(comptime T: type, node: *ListNode(T), index: i32) ?*ListNode(T) {
var head: ?*ListNode(T) = node;
var i: i32 = 0;
while (i < index) : (i += 1) {
head = head.?.next;
if (head == null) return null;
if (head) |cur| {
head = cur.next;
} else {
return null;
}
}
return head;
}
@@ -1293,12 +1295,12 @@ comments: true
```zig title="linked_list.zig"
// 在链表中查找值为 target 的首个节点
fn find(node: ?*inc.ListNode(i32), target: i32) i32 {
var head = node;
fn find(comptime T: type, node: *ListNode(T), target: T) i32 {
var head: ?*ListNode(T) = node;
var index: i32 = 0;
while (head != null) {
if (head.?.val == target) return index;
head = head.?.next;
while (head) |cur| {
if (cur.val == target) return index;
head = cur.next;
index += 1;
}
return -1;
+135 -99
View File
@@ -2372,121 +2372,157 @@ comments: true
```zig title="my_list.zig"
// 列表类
fn MyList(comptime T: type) type {
return struct {
const Self = @This();
arr: []T = undefined, // 数组(存储列表元素)
arrCapacity: usize = 10, // 列表容量
numSize: usize = 0, // 列表长度(当前元素数量)
extendRatio: usize = 2, // 每次列表扩容的倍数
mem_arena: ?std.heap.ArenaAllocator = null,
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
const MyList = struct {
const Self = @This();
// 构造函数(分配内存+初始化列表
pub fn init(self: *Self, allocator: std.mem.Allocator) !void {
if (self.mem_arena == null) {
self.mem_arena = std.heap.ArenaAllocator.init(allocator);
self.mem_allocator = self.mem_arena.?.allocator();
}
self.arr = try self.mem_allocator.alloc(T, self.arrCapacity);
@memset(self.arr, @as(T, 0));
}
items: []i32, // 数组(存储列表元素
capacity: usize, // 列表容量
allocator: std.mem.Allocator, // 内存分配器
// 析构函数(释放内存)
pub fn deinit(self: *Self) void {
if (self.mem_arena == null) return;
self.mem_arena.?.deinit();
}
extend_ratio: usize = 2, // 每次列表扩容的倍数
// 获取列表长度(当前元素数量
pub fn size(self: *Self) usize {
return self.numSize;
}
// 构造函数(分配内存+初始化列表
pub fn init(allocator: std.mem.Allocator) Self {
return Self{
.items = &[_]i32{},
.capacity = 0,
.allocator = allocator,
};
}
// 获取列表容量
pub fn capacity(self: *Self) usize {
return self.arrCapacity;
}
// 析构函数(释放内存)
pub fn deinit(self: Self) void {
self.allocator.free(self.allocatedSlice());
}
// 访问元素
pub fn get(self: *Self, index: usize) T {
// 索引如果越界,则抛出异常,下同
if (index < 0 or index >= self.size()) @panic("索引越界");
return self.arr[index];
}
// 在尾部添加元素
pub fn add(self: *Self, item: i32) !void {
// 元素数量超出容量时,触发扩容机制
const newlen = self.items.len + 1;
try self.ensureTotalCapacity(newlen);
// 更新元素
pub fn set(self: *Self, index: usize, num: T) void {
// 索引如果越界,则抛出异常,下同
if (index < 0 or index >= self.size()) @panic("索引越界");
self.arr[index] = num;
}
self.items.len += 1;
const new_item_ptr = &self.items[self.items.len - 1];
new_item_ptr.* = item;
}
// 在尾部添加元素
pub fn add(self: *Self, num: T) !void {
// 元素数量超出容量时,触发扩容机制
if (self.size() == self.capacity()) try self.extendCapacity();
self.arr[self.size()] = num;
// 更新元素数量
self.numSize += 1;
}
// 获取列表长度(当前元素数量)
pub fn getSize(self: *Self) usize {
return self.items.len;
}
// 在中间插入元素
pub fn insert(self: *Self, index: usize, num: T) !void {
if (index < 0 or index >= self.size()) @panic("索引越界");
// 元素数量超出容量时,触发扩容机制
if (self.size() == self.capacity()) try self.extendCapacity();
// 将索引 index 以及之后的元素都向后移动一位
var j = self.size() - 1;
while (j >= index) : (j -= 1) {
self.arr[j + 1] = self.arr[j];
// 获取列表容量
pub fn getCapacity(self: *Self) usize {
return self.capacity;
}
// 访问元素
pub fn get(self: *Self, index: usize) i32 {
// 索引如果越界,则抛出异常,下同
if (index < 0 or index >= self.items.len) {
@panic("索引越界");
}
return self.items[index];
}
// 更新元素
pub fn set(self: *Self, index: usize, num: i32) void {
// 索引如果越界,则抛出异常,下同
if (index < 0 or index >= self.items.len) {
@panic("索引越界");
}
self.items[index] = num;
}
// 在中间插入元素
pub fn insert(self: *Self, index: usize, item: i32) !void {
if (index < 0 or index >= self.items.len) {
@panic("索引越界");
}
// 元素数量超出容量时,触发扩容机制
const newlen = self.items.len + 1;
try self.ensureTotalCapacity(newlen);
// 将索引 index 以及之后的元素都向后移动一位
self.items.len += 1;
var i = self.items.len - 1;
while (i >= index) : (i -= 1) {
self.items[i] = self.items[i - 1];
}
self.items[index] = item;
}
// 删除元素
pub fn remove(self: *Self, index: usize) i32 {
if (index < 0 or index >= self.getSize()) {
@panic("索引越界");
}
// 将索引 index 之后的元素都向前移动一位
const item = self.items[index];
var i = index;
while (i < self.items.len - 1) : (i += 1) {
self.items[i] = self.items[i + 1];
}
self.items.len -= 1;
// 返回被删除的元素
return item;
}
// 将列表转换为数组
pub fn toArraySlice(self: *Self) ![]i32 {
return self.toOwnedSlice(false);
}
// 返回新的切片并设置是否要重置或清空列表容器
pub fn toOwnedSlice(self: *Self, clear: bool) ![]i32 {
const allocator = self.allocator;
const old_memory = self.allocatedSlice();
if (allocator.remap(old_memory, self.items.len)) |new_items| {
if (clear) {
self.* = init(allocator);
}
self.arr[index] = num;
// 更新元素数量
self.numSize += 1;
return new_items;
}
// 删除元素
pub fn remove(self: *Self, index: usize) T {
if (index < 0 or index >= self.size()) @panic("索引越界");
var num = self.arr[index];
// 将索引 index 之后的元素都向前移动一位
var j = index;
while (j < self.size() - 1) : (j += 1) {
self.arr[j] = self.arr[j + 1];
}
// 更新元素数量
self.numSize -= 1;
// 返回被删除的元素
return num;
const new_memory = try allocator.alloc(i32, self.items.len);
@memcpy(new_memory, self.items);
if (clear) {
self.clearAndFree();
}
return new_memory;
}
// 列表扩容
pub fn extendCapacity(self: *Self) !void {
// 新建一个长度为 size * extendRatio 的数组,并将原数组复制到新数组
var newCapacity = self.capacity() * self.extendRatio;
var extend = try self.mem_allocator.alloc(T, newCapacity);
@memset(extend, @as(T, 0));
// 将原数组中的所有元素复制到新数组
std.mem.copy(T, extend, self.arr);
self.arr = extend;
// 更新列表容量
self.arrCapacity = newCapacity;
}
// 列表扩容
fn ensureTotalCapacity(self: *Self, new_capacity: usize) !void {
if (self.capacity >= new_capacity) return;
const capcacity = if (self.capacity == 0) 10 else self.capacity;
const better_capacity = capcacity * self.extend_ratio;
// 将列表转换为数组
pub fn toArray(self: *Self) ![]T {
// 仅转换有效长度范围内的列表元素
var arr = try self.mem_allocator.alloc(T, self.size());
@memset(arr, @as(T, 0));
for (arr, 0..) |*num, i| {
num.* = self.get(i);
}
return arr;
const old_memory = self.allocatedSlice();
if (self.allocator.remap(old_memory, better_capacity)) |new_memory| {
self.items.ptr = new_memory.ptr;
self.capacity = new_memory.len;
} else {
const new_memory = try self.allocator.alloc(i32, better_capacity);
@memcpy(new_memory[0..self.items.len], self.items);
self.allocator.free(old_memory);
self.items.ptr = new_memory.ptr;
self.capacity = new_memory.len;
}
};
}
}
fn clearAndFree(self: *Self, allocator: std.mem.Allocator) void {
allocator.free(self.allocatedSlice());
self.items.len = 0;
self.capacity = 0;
}
fn allocatedSlice(self: Self) []i32 {
return self.items.ptr[0..self.capacity];
}
};
```
??? pythontutor "可视化运行"