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
@@ -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 "視覺化執行"