code: update zig 0.14.1 for the chapter of array_and_linkedlist and computational_complexity (#1787)

* update zig array list chapter

* update not need change codes.

* fix some pr issues and update time space chapter
This commit is contained in:
MetaSky
2025-08-06 02:33:00 +08:00
committed by GitHub
parent 0918fd06f2
commit 803c0e09c7
22 changed files with 836 additions and 627 deletions

View File

@@ -1,2 +1,4 @@
zig-out/
zig-cache/
zig-out
zig-cache
.zig-cache
!/.vscode/

14
codes/zig/.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,14 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug",
"type": "lldb",
"request": "launch",
"program": "${workspaceFolder}/zig-out/bin/${fileBasenameNoExtension}",
"args": [],
"cwd": "${workspaceFolder}",
"preLaunchTask": "build"
}
]
}

3
codes/zig/.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"zig.testArgs": ["build", "test", "-Dtest-filter=${filter}"]
}

10
codes/zig/.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,10 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"type": "shell",
"command": "zig build",
}
]
}

View File

@@ -1,221 +1,169 @@
// File: build.zig
// Created Time: 2023-01-07
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
//! Zig Version: 0.14.1
//! Build Command: zig build
//! Run Command: zig build run | zig build run_*
//! Test Command: zig build test | zig build test -Dtest-filter=*
const std = @import("std");
// Zig Version: 0.11.0
// Zig Build Command: zig build -Doptimize=ReleaseSafe
// Zig Run Command: zig build run_* -Doptimize=ReleaseSafe
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const group_name_path = .{
// Source File: "chapter_computational_complexity/time_complexity.zig"
// Run Command: zig build run_time_complexity -Doptimize=ReleaseSafe
.{ .name = "time_complexity", .path = "chapter_computational_complexity/time_complexity.zig" },
// Source File: "chapter_computational_complexity/worst_best_time_complexity.zig"
// Run Command: zig build run_worst_best_time_complexity -Doptimize=ReleaseSafe
.{ .name = "worst_best_time_complexity", .path = "chapter_computational_complexity/worst_best_time_complexity.zig" },
// Source File: "chapter_computational_complexity/space_complexity.zig"
// Run Command: zig build run_space_complexity -Doptimize=ReleaseSafe
.{ .name = "space_complexity", .path = "chapter_computational_complexity/space_complexity.zig" },
// Source File: "chapter_computational_complexity/iteration.zig"
// Run Command: zig build run_iteration -Doptimize=ReleaseFast
.{ .name = "iteration", .path = "chapter_computational_complexity/iteration.zig" },
// Source File: "chapter_computational_complexity/recursion.zig"
// Run Command: zig build run_recursion -Doptimize=ReleaseFast
.{ .name = "recursion", .path = "chapter_computational_complexity/recursion.zig" },
// Source File: "chapter_array_and_linkedlist/array.zig"
// Run Command: zig build run_array -Doptimize=ReleaseSafe
.{ .name = "array", .path = "chapter_array_and_linkedlist/array.zig" },
// Source File: "chapter_array_and_linkedlist/linked_list.zig"
// Run Command: zig build run_linked_list -Doptimize=ReleaseSafe
.{ .name = "linked_list", .path = "chapter_array_and_linkedlist/linked_list.zig" },
// Source File: "chapter_array_and_linkedlist/list.zig"
// Run Command: zig build run_list -Doptimize=ReleaseSafe
.{ .name = "list", .path = "chapter_array_and_linkedlist/list.zig" },
// Source File: "chapter_array_and_linkedlist/my_list.zig"
// Run Command: zig build run_my_list -Doptimize=ReleaseSafe
.{ .name = "my_list", .path = "chapter_array_and_linkedlist/my_list.zig" },
// Source File: "chapter_stack_and_queue/stack.zig"
// Run Command: zig build run_stack -Doptimize=ReleaseSafe
.{ .name = "stack", .path = "chapter_stack_and_queue/stack.zig" },
// Source File: "chapter_stack_and_queue/linkedlist_stack.zig"
// Run Command: zig build run_linkedlist_stack -Doptimize=ReleaseSafe
.{ .name = "linkedlist_stack", .path = "chapter_stack_and_queue/linkedlist_stack.zig" },
// Source File: "chapter_stack_and_queue/array_stack.zig"
// Run Command: zig build run_array_stack -Doptimize=ReleaseSafe
.{ .name = "array_stack", .path = "chapter_stack_and_queue/array_stack.zig" },
// Source File: "chapter_stack_and_queue/queue.zig"
// Run Command: zig build run_queue -Doptimize=ReleaseSafe
.{ .name = "queue", .path = "chapter_stack_and_queue/queue.zig" },
// Source File: "chapter_stack_and_queue/array_queue.zig"
// Run Command: zig build run_array_queue -Doptimize=ReleaseSafe
.{ .name = "array_queue", .path = "chapter_stack_and_queue/array_queue.zig" },
// Source File: "chapter_stack_and_queue/linkedlist_queue.zig"
// Run Command: zig build run_linkedlist_queue -Doptimize=ReleaseSafe
.{ .name = "linkedlist_queue", .path = "chapter_stack_and_queue/linkedlist_queue.zig" },
// Source File: "chapter_stack_and_queue/deque.zig"
// Run Command: zig build run_deque -Doptimize=ReleaseSafe
.{ .name = "deque", .path = "chapter_stack_and_queue/deque.zig" },
// Source File: "chapter_stack_and_queue/linkedlist_deque.zig"
// Run Command: zig build run_linkedlist_deque -Doptimize=ReleaseSafe
.{ .name = "linkedlist_deque", .path = "chapter_stack_and_queue/linkedlist_deque.zig" },
// Source File: "chapter_hashing/hash_map.zig"
// Run Command: zig build run_hash_map -Doptimize=ReleaseSafe
.{ .name = "hash_map", .path = "chapter_hashing/hash_map.zig" },
// Source File: "chapter_hashing/array_hash_map.zig"
// Run Command: zig build run_array_hash_map -Doptimize=ReleaseSafe
.{ .name = "array_hash_map", .path = "chapter_hashing/array_hash_map.zig" },
// Source File: "chapter_tree/binary_tree.zig"
// Run Command: zig build run_binary_tree -Doptimize=ReleaseSafe
.{ .name = "binary_tree", .path = "chapter_tree/binary_tree.zig" },
// Source File: "chapter_tree/binary_tree_bfs.zig"
// Run Command: zig build run_binary_tree_bfs -Doptimize=ReleaseSafe
.{ .name = "binary_tree_bfs", .path = "chapter_tree/binary_tree_bfs.zig" },
// Source File: "chapter_tree/binary_tree_dfs.zig"
// Run Command: zig build run_binary_tree_dfs -Doptimize=ReleaseSafe
.{ .name = "binary_tree_dfs", .path = "chapter_tree/binary_tree_dfs.zig" },
// Source File: "chapter_tree/binary_search_tree.zig"
// Run Command: zig build run_binary_search_tree -Doptimize=ReleaseSafe
.{ .name = "binary_search_tree", .path = "chapter_tree/binary_search_tree.zig" },
// Source File: "chapter_tree/avl_tree.zig"
// Run Command: zig build run_avl_tree -Doptimize=ReleaseSafe
.{ .name = "avl_tree", .path = "chapter_tree/avl_tree.zig" },
// Source File: "chapter_heap/heap.zig"
// Run Command: zig build run_heap -Doptimize=ReleaseSafe
.{ .name = "heap", .path = "chapter_heap/heap.zig" },
// Source File: "chapter_heap/my_heap.zig"
// Run Command: zig build run_my_heap -Doptimize=ReleaseSafe
.{ .name = "my_heap", .path = "chapter_heap/my_heap.zig" },
// Source File: "chapter_searching/linear_search.zig"
// Run Command: zig build run_linear_search -Doptimize=ReleaseSafe
.{ .name = "linear_search", .path = "chapter_searching/linear_search.zig" },
// Source File: "chapter_searching/binary_search.zig"
// Run Command: zig build run_binary_search -Doptimize=ReleaseSafe
.{ .name = "binary_search", .path = "chapter_searching/binary_search.zig" },
// Source File: "chapter_searching/hashing_search.zig"
// Run Command: zig build run_hashing_search -Doptimize=ReleaseSafe
.{ .name = "hashing_search", .path = "chapter_searching/hashing_search.zig" },
// Source File: "chapter_searching/two_sum.zig"
// Run Command: zig build run_two_sum -Doptimize=ReleaseSafe
.{ .name = "two_sum", .path = "chapter_searching/two_sum.zig" },
// Source File: "chapter_sorting/bubble_sort.zig"
// Run Command: zig build run_bubble_sort -Doptimize=ReleaseSafe
.{ .name = "bubble_sort", .path = "chapter_sorting/bubble_sort.zig" },
// Source File: "chapter_sorting/insertion_sort.zig"
// Run Command: zig build run_insertion_sort -Doptimize=ReleaseSafe
.{ .name = "insertion_sort", .path = "chapter_sorting/insertion_sort.zig" },
// Source File: "chapter_sorting/quick_sort.zig"
// Run Command: zig build run_quick_sort -Doptimize=ReleaseSafe
.{ .name = "quick_sort", .path = "chapter_sorting/quick_sort.zig" },
// Source File: "chapter_sorting/merge_sort.zig"
// Run Command: zig build run_merge_sort -Doptimize=ReleaseSafe
.{ .name = "merge_sort", .path = "chapter_sorting/merge_sort.zig" },
// Source File: "chapter_sorting/radix_sort.zig"
// Run Command: zig build run_radix_sort -Doptimize=ReleaseSafe
.{ .name = "radix_sort", .path = "chapter_sorting/radix_sort.zig" },
// Source File: "chapter_dynamic_programming/climbing_stairs_backtrack.zig"
// Run Command: zig build run_climbing_stairs_backtrack -Doptimize=ReleaseSafe
.{ .name = "climbing_stairs_backtrack", .path = "chapter_dynamic_programming/climbing_stairs_backtrack.zig" },
// Source File: "chapter_dynamic_programming/climbing_stairs_constraint_dp.zig"
// Run Command: zig build run_climbing_stairs_constraint_dp -Doptimize=ReleaseSafe
.{ .name = "climbing_stairs_constraint_dp", .path = "chapter_dynamic_programming/climbing_stairs_constraint_dp.zig" },
// Source File: "chapter_dynamic_programming/climbing_stairs_dfs_mem.zig"
// Run Command: zig build run_climbing_stairs_dfs_mem -Doptimize=ReleaseSafe
.{ .name = "climbing_stairs_dfs_mem", .path = "chapter_dynamic_programming/climbing_stairs_dfs_mem.zig" },
// Source File: "chapter_dynamic_programming/climbing_stairs_dfs.zig"
// Run Command: zig build run_climbing_stairs_dfs -Doptimize=ReleaseSafe
.{ .name = "climbing_stairs_dfs", .path = "chapter_dynamic_programming/climbing_stairs_dfs.zig" },
// Source File: "chapter_dynamic_programming/climbing_stairs_dp.zig"
// Run Command: zig build run_climbing_stairs_dp -Doptimize=ReleaseSafe
.{ .name = "climbing_stairs_dp", .path = "chapter_dynamic_programming/climbing_stairs_dp.zig" },
// Source File: "chapter_dynamic_programming/coin_change_ii.zig"
// Run Command: zig build run_coin_change_ii -Doptimize=ReleaseSafe
.{ .name = "coin_change_ii", .path = "chapter_dynamic_programming/coin_change_ii.zig" },
// Source File: "chapter_dynamic_programming/coin_change.zig"
// Run Command: zig build run_coin_change -Doptimize=ReleaseSafe
.{ .name = "coin_change", .path = "chapter_dynamic_programming/coin_change.zig" },
// Source File: "chapter_dynamic_programming/edit_distance.zig"
// Run Command: zig build run_edit_distance -Doptimize=ReleaseSafe
.{ .name = "edit_distance", .path = "chapter_dynamic_programming/edit_distance.zig" },
// Source File: "chapter_dynamic_programming/knapsack.zig"
// Run Command: zig build run_knapsack -Doptimize=ReleaseSafe
.{ .name = "knapsack", .path = "chapter_dynamic_programming/knapsack.zig" },
// Source File: "chapter_dynamic_programming/min_cost_climbing_stairs_dp.zig"
// Run Command: zig build run_min_cost_climbing_stairs_dp -Doptimize=ReleaseSafe
.{ .name = "min_cost_climbing_stairs_dp", .path = "chapter_dynamic_programming/min_cost_climbing_stairs_dp.zig" },
// Source File: "chapter_dynamic_programming/min_path_sum.zig"
// Run Command: zig build run_min_path_sum -Doptimize=ReleaseSafe
.{ .name = "min_path_sum", .path = "chapter_dynamic_programming/min_path_sum.zig" },
// Source File: "chapter_dynamic_programming/unbounded_knapsack.zig"
// Run Command: zig build run_unbounded_knapsack -Doptimize=ReleaseSafe
.{ .name = "unbounded_knapsack", .path = "chapter_dynamic_programming/unbounded_knapsack.zig" },
const chapters = [_][]const u8{
"chapter_computational_complexity",
"chapter_array_and_linkedlist",
"chapter_stack_and_queue",
"chapter_hashing",
"chapter_tree",
"chapter_heap",
"chapter_searching",
"chapter_sorting",
"chapter_dynamic_programming",
};
inline for (group_name_path) |name_path| {
const exe = b.addExecutable(.{
.name = name_path.name,
.root_source_file = .{ .path = name_path.path },
.target = target,
.optimize = optimize,
});
exe.addModule("include", b.addModule("", .{
.source_file = .{ .path = "include/include.zig" },
}));
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd.addArgs(args);
const run_step = b.step("run_" ++ name_path.name, "Run the app");
run_step.dependOn(&run_cmd.step);
const test_step = b.step("test", "Run unit tests");
const test_filters = b.option([]const []const u8, "test-filter", "Skip tests that do not match any filter") orelse &[0][]const u8{};
buildChapterExeModules(b, target, optimize, &chapters, test_step, test_filters);
buildMainExeModule(b, target, optimize);
}
fn buildChapterExeModules(
b: *std.Build,
target: std.Build.ResolvedTarget,
optimize: std.builtin.OptimizeMode,
chapter_dirs: []const []const u8,
test_step: *std.Build.Step,
test_filters: []const []const u8,
) void {
for (chapter_dirs) |chapter_dir_name| {
const chapter_dir_path = std.fs.path.join(b.allocator, &[_][]const u8{chapter_dir_name}) catch continue;
var chapter_dir = std.fs.cwd().openDir(chapter_dir_path, .{ .iterate = true }) catch continue;
defer chapter_dir.close();
var it = chapter_dir.iterate();
while (it.next() catch continue) |chapter_dir_entry| {
if (chapter_dir_entry.kind != .file or !std.mem.endsWith(u8, chapter_dir_entry.name, ".zig")) continue;
const exe_mod = buildExeModuleFromChapterDirEntry(b, target, optimize, chapter_dir_name, chapter_dir_entry) catch continue;
addTestStepToExeModule(b, test_step, exe_mod, test_filters);
}
}
}
fn buildExeModuleFromChapterDirEntry(
b: *std.Build,
target: std.Build.ResolvedTarget,
optimize: std.builtin.OptimizeMode,
chapter_dir_name: []const u8,
chapter_dir_entry: std.fs.Dir.Entry,
) !*std.Build.Module {
const zig_file_path = try std.fs.path.join(b.allocator, &[_][]const u8{ chapter_dir_name, chapter_dir_entry.name });
const zig_file_name = chapter_dir_entry.name[0 .. chapter_dir_entry.name.len - 4]; // abstract zig file name from xxx.zig
// 这里临时只添加数组和链表章节部分,后续修改完后全部放开
const new_algo_names = [_][]const u8{
"array",
"linked_list",
"list",
"my_list",
"iteration",
"recursion",
"space_complexity",
"time_complexity",
"worst_best_time_complexity",
};
var can_run = false;
for (new_algo_names) |name| {
if (std.mem.eql(u8, zig_file_name, name)) {
can_run = true;
}
}
if (!can_run) {
return error.CanNotRunUseOldZigCodes;
}
// std.debug.print("now run zig file name = {s}\n", .{zig_file_name});
const exe_mod = b.createModule(.{
.root_source_file = b.path(zig_file_path),
.target = target,
.optimize = optimize,
});
const exe = b.addExecutable(.{
.name = zig_file_name,
.root_module = exe_mod,
});
const utils_mod = createUtilsModule(b, target, optimize);
exe_mod.addImport("utils", utils_mod);
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const step_name = try std.fmt.allocPrint(b.allocator, "run_{s}", .{zig_file_name});
const step_desc = try std.fmt.allocPrint(b.allocator, "Run {s}/{s}.zig", .{ chapter_dir_name, zig_file_name });
const run_step = b.step(step_name, step_desc);
run_step.dependOn(&run_cmd.step);
return exe_mod;
}
fn buildMainExeModule(
b: *std.Build,
target: std.Build.ResolvedTarget,
optimize: std.builtin.OptimizeMode,
) void {
const exe_mod = b.createModule(.{
.root_source_file = b.path("main.zig"),
.target = target,
.optimize = optimize,
});
const utils_mod = createUtilsModule(b, target, optimize);
exe_mod.addImport("utils", utils_mod);
const exe = b.addExecutable(.{
.name = "main",
.root_module = exe_mod,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run all hello algo zig");
run_step.dependOn(&run_cmd.step);
}
fn createUtilsModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module {
const utils_mod = b.createModule(.{
.root_source_file = b.path("utils/utils.zig"),
.target = target,
.optimize = optimize,
});
return utils_mod;
}
fn addTestStepToExeModule(b: *std.Build, test_step: *std.Build.Step, exe_mod: *std.Build.Module, test_filters: []const []const u8) void {
const exe_unit_tests = b.addTest(.{
.root_module = exe_mod,
.filters = test_filters,
});
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
test_step.dependOn(&run_exe_unit_tests.step);
}

View File

@@ -1,26 +1,28 @@
// File: array.zig
// Created Time: 2023-01-07
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const inc = @import("include");
const utils = @import("utils");
// 随机访问元素
pub fn randomAccess(nums: []i32) i32 {
pub 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;
}
// 扩展数组长度
pub fn extend(mem_allocator: std.mem.Allocator, nums: []i32, enlarge: usize) ![]i32 {
pub 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;
}
@@ -46,18 +48,26 @@ pub fn remove(nums: []i32, index: usize) void {
}
// 遍历数组
pub fn traverse(nums: []i32) void {
pub 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;
}
}
// 在数组中查找指定元素
@@ -69,49 +79,53 @@ pub fn find(nums: []i32, target: i32) i32 {
}
// Driver Code
pub fn main() !void {
// 初始化内存分配器
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer mem_arena.deinit();
const mem_allocator = mem_arena.allocator();
pub fn run() !void {
// 初始化数组
var arr = [_]i32{0} ** 5;
std.debug.print("数组 arr = ", .{});
inc.PrintUtil.printArray(i32, &arr);
const arr = [_]i32{0} ** 5;
std.debug.print("数组 arr = {}\n", .{utils.fmt.slice(&arr)});
// 数组切片
var array = [_]i32{ 1, 3, 2, 5, 4 };
var known_at_runtime_zero: usize = 0;
var nums = array[known_at_runtime_zero..];
std.debug.print("\n数组 nums = ", .{});
inc.PrintUtil.printArray(i32, nums);
_ = &known_at_runtime_zero;
var nums = array[known_at_runtime_zero..array.len]; // 通过 known_at_runtime_zero 运行时变量将指针变切片
std.debug.print("数组 nums = {}\n", .{utils.fmt.slice(nums)});
// 随机访问
var randomNum = randomAccess(nums);
std.debug.print("\n在 nums 中获取随机元素 {}", .{randomNum});
const randomNum = randomAccess(nums);
std.debug.print("在 nums 中获取随机元素 {}\n", .{randomNum});
// 初始化内存分配器
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
// 长度扩展
nums = try extend(mem_allocator, nums, 3);
std.debug.print("\n将数组长度扩展至 8 ,得到 nums = ", .{});
inc.PrintUtil.printArray(i32, nums);
nums = try extend(allocator, nums, 3);
std.debug.print("将数组长度扩展至 8 ,得到 nums = {}\n", .{utils.fmt.slice(nums)});
// 插入元素
insert(nums, 6, 3);
std.debug.print("\n在索引 3 处插入数字 6 ,得到 nums = ", .{});
inc.PrintUtil.printArray(i32, nums);
std.debug.print("在索引 3 处插入数字 6 ,得到 nums = {}\n", .{utils.fmt.slice(nums)});
// 删除元素
remove(nums, 2);
std.debug.print("\n删除索引 2 处的元素,得到 nums = ", .{});
inc.PrintUtil.printArray(i32, nums);
std.debug.print("删除索引 2 处的元素,得到 nums = {}\n", .{utils.fmt.slice(nums)});
// 遍历数组
traverse(nums);
// 查找元素
var index = find(nums, 3);
std.debug.print("\n在 nums 中查找元素 3 ,得到索引 = {}\n", .{index});
const index = find(nums, 3);
std.debug.print("在 nums 中查找元素 3 ,得到索引 = {}\n", .{index});
_ = try std.io.getStdIn().reader().readByte();
std.debug.print("\n", .{});
}
pub fn main() !void {
try run();
}
test "array" {
try run();
}

View File

@@ -1,84 +1,106 @@
// File: linked_list.zig
// Created Time: 2023-01-07
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const inc = @import("include");
const utils = @import("utils");
const ListNode = utils.ListNode;
// 在链表的节点 n0 之后插入节点 P
pub fn insert(n0: ?*inc.ListNode(i32), P: ?*inc.ListNode(i32)) void {
var n1 = n0.?.next;
P.?.next = n1;
n0.?.next = P;
pub fn insert(comptime T: type, n0: *ListNode(T), P: *ListNode(T)) void {
const n1 = n0.next;
P.next = n1;
n0.next = P;
}
// 删除链表的节点 n0 之后的首个节点
pub 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;
pub 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;
}
// 访问链表中索引为 index 的节点
pub fn access(node: ?*inc.ListNode(i32), index: i32) ?*inc.ListNode(i32) {
var head = node;
pub 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;
}
// 在链表中查找值为 target 的首个节点
pub fn find(node: ?*inc.ListNode(i32), target: i32) i32 {
var head = node;
pub 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;
}
// Driver Code
pub fn main() !void {
// 初始化链表
// 初始化各个节点
var n0 = inc.ListNode(i32){.val = 1};
var n1 = inc.ListNode(i32){.val = 3};
var n2 = inc.ListNode(i32){.val = 2};
var n3 = inc.ListNode(i32){.val = 5};
var n4 = inc.ListNode(i32){.val = 4};
pub fn run() void {
// 初始化各个节点
var n0 = ListNode(i32){ .val = 1 };
var n1 = ListNode(i32){ .val = 3 };
var n2 = ListNode(i32){ .val = 2 };
var n3 = ListNode(i32){ .val = 5 };
var n4 = ListNode(i32){ .val = 4 };
// 构建节点之间的引用
n0.next = &n1;
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
std.debug.print("初始化的链表为", .{});
try inc.PrintUtil.printLinkedList(i32, &n0);
std.debug.print(
"初始化的链表为 {}\n",
.{utils.fmt.linkedList(i32, &n0)},
);
// 插入节点
var tmp = inc.ListNode(i32){.val = 0};
insert(&n0, &tmp);
std.debug.print("插入节点后的链表为", .{});
try inc.PrintUtil.printLinkedList(i32, &n0);
var tmp = ListNode(i32){ .val = 0 };
insert(i32, &n0, &tmp);
std.debug.print(
"插入节点后的链表为 {}\n",
.{utils.fmt.linkedList(i32, &n0)},
);
// 删除节点
remove(&n0);
std.debug.print("删除节点后的链表为", .{});
try inc.PrintUtil.printLinkedList(i32, &n0);
remove(i32, &n0);
std.debug.print(
"删除节点后的链表为{}\n",
.{utils.fmt.linkedList(i32, &n0)},
);
// 访问节点
var node = access(&n0, 3);
std.debug.print("链表中索引 3 处的节点的值 = {}\n", .{node.?.val});
const node = access(i32, &n0, 3);
std.debug.print(
"链表中索引 3 处的节点的值 = {}\n",
.{node.?.val},
);
// 查找节点
var index = find(&n0, 2);
std.debug.print("链表中值为 2 的节点的索引 = {}\n", .{index});
const index = find(i32, &n0, 2);
std.debug.print(
"链表中值为 2 的节点的索引 = {}\n",
.{index},
);
_ = try std.io.getStdIn().reader().readByte();
}
std.debug.print("\n", .{});
}
pub fn main() void {
run();
}
test "linked_list" {
run();
}

View File

@@ -1,33 +1,30 @@
// File: list.zig
// Created Time: 2023-01-07
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const inc = @import("include");
const utils = @import("utils");
// Driver Code
pub fn main() !void {
pub fn run() !void {
// 初始化列表
var nums = std.ArrayList(i32).init(std.heap.page_allocator);
// 延迟释放内存
defer nums.deinit();
defer nums.deinit(); // 延迟释放内存
try nums.appendSlice(&[_]i32{ 1, 3, 2, 5, 4 });
std.debug.print("列表 nums = ", .{});
inc.PrintUtil.printList(i32, nums);
std.debug.print("列表 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 访问元素
var num = nums.items[1];
std.debug.print("\n访问索引 1 处的元素,得到 num = {}", .{num});
const num = nums.items[1];
std.debug.print("访问索引 1 处的元素,得到 num = {}\n", .{num});
// 更新元素
nums.items[1] = 0;
std.debug.print("\n将索引 1 处的元素更新为 0 ,得到 nums = ", .{});
inc.PrintUtil.printList(i32, nums);
std.debug.print("将索引 1 处的元素更新为 0 ,得到 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 清空列表
nums.clearRetainingCapacity();
std.debug.print("\n清空列表后 nums = ", .{});
inc.PrintUtil.printList(i32, nums);
std.debug.print("清空列表后 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 在尾部添加元素
try nums.append(1);
@@ -35,25 +32,23 @@ pub fn main() !void {
try nums.append(2);
try nums.append(5);
try nums.append(4);
std.debug.print("\n添加元素后 nums = ", .{});
inc.PrintUtil.printList(i32, nums);
std.debug.print("添加元素后 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 在中间插入元素
try nums.insert(3, 6);
std.debug.print("\n在索引 3 处插入数字 6 ,得到 nums = ", .{});
inc.PrintUtil.printList(i32, nums);
std.debug.print("在索引 3 处插入数字 6 ,得到 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 删除元素
_ = nums.orderedRemove(3);
std.debug.print("\n删除索引 3 处的元素,得到 nums = ", .{});
inc.PrintUtil.printList(i32, nums);
std.debug.print("删除索引 3 处的元素,得到 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 通过索引遍历列表
var count: i32 = 0;
var i: i32 = 0;
var i: usize = 0;
while (i < nums.items.len) : (i += 1) {
count += nums[i];
count += nums.items[i];
}
// 直接遍历列表元素
count = 0;
for (nums.items) |x| {
@@ -65,14 +60,19 @@ pub fn main() !void {
defer nums1.deinit();
try nums1.appendSlice(&[_]i32{ 6, 8, 7, 10, 9 });
try nums.insertSlice(nums.items.len, nums1.items);
std.debug.print("\n将列表 nums1 拼接到 nums 之后,得到 nums = ", .{});
inc.PrintUtil.printList(i32, nums);
std.debug.print("将列表 nums1 拼接到 nums 之后,得到 nums = {}\n", .{utils.fmt.slice(nums.items)});
// 排序列表
std.mem.sort(i32, nums.items, {}, comptime std.sort.asc(i32));
std.debug.print("\n排序列表后 nums = ", .{});
inc.PrintUtil.printList(i32, nums);
std.debug.print("排序列表后 nums = {}\n", .{utils.fmt.slice(nums.items)});
_ = try std.io.getStdIn().reader().readByte();
std.debug.print("\n", .{});
}
pub fn main() !void {
try run();
}
test "list" {
try run();
}

View File

@@ -1,132 +1,171 @@
// File: my_list.zig
// Created Time: 2023-01-08
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const inc = @import("include");
const utils = @import("utils");
// 列表类
pub 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];
}
};
// Driver Code
pub fn main() !void {
pub fn run() !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// 初始化列表
var nums = MyList(i32){};
try nums.init(std.heap.page_allocator);
var nums = MyList.init(allocator);
// 延迟释放内存
defer nums.deinit();
@@ -136,28 +175,36 @@ pub fn main() !void {
try nums.add(2);
try nums.add(5);
try nums.add(4);
std.debug.print("列表 nums = ", .{});
inc.PrintUtil.printArray(i32, try nums.toArray());
std.debug.print(" ,容量 = {} ,长度 = {}", .{nums.capacity(), nums.size()});
std.debug.print("列表 nums = {} ,容量 = {} ,长度 = {}\n", .{
utils.fmt.slice(nums.items),
nums.getCapacity(),
nums.getSize(),
});
// 在中间插入元素
try nums.insert(3, 6);
std.debug.print("\n在索引 3 处插入数字 6 ,得到 nums = ", .{});
inc.PrintUtil.printArray(i32, try nums.toArray());
std.debug.print(
"在索引 3 处插入数字 6 ,得到 nums = {}\n",
.{utils.fmt.slice(nums.items)},
);
// 删除元素
_ = nums.remove(3);
std.debug.print("\n删除索引 3 处的元素,得到 nums = ", .{});
inc.PrintUtil.printArray(i32, try nums.toArray());
std.debug.print(
"删除索引 3 处的元素,得到 nums = {}\n",
.{utils.fmt.slice(nums.items)},
);
// 访问元素
var num = nums.get(1);
std.debug.print("\n访问索引 1 处的元素,得到 num = {}", .{num});
const num = nums.get(1);
std.debug.print("访问索引 1 处的元素,得到 num = {}\n", .{num});
// 更新元素
nums.set(1, 0);
std.debug.print("\n将索引 1 处的元素更新为 0 ,得到 nums = ", .{});
inc.PrintUtil.printArray(i32, try nums.toArray());
std.debug.print(
"将索引 1 处的元素更新为 0 ,得到 nums = {}\n",
.{utils.fmt.slice(nums.items)},
);
// 测试扩容机制
var i: i32 = 0;
@@ -165,9 +212,22 @@ pub fn main() !void {
// 在 i = 5 时,列表长度将超出列表容量,此时触发扩容机制
try nums.add(i);
}
std.debug.print("\n扩容后的列表 nums = ", .{});
inc.PrintUtil.printArray(i32, try nums.toArray());
std.debug.print(" ,容量 = {} ,长度 = {}\n", .{nums.capacity(), nums.size()});
std.debug.print(
"扩容后的列表 nums = {} ,容量 = {} ,长度 = {}\n",
.{
utils.fmt.slice(nums.items),
nums.getCapacity(),
nums.getSize(),
},
);
_ = try std.io.getStdIn().reader().readByte();
std.debug.print("\n", .{});
}
pub fn main() !void {
try run();
}
test "my_list" {
try run();
}

View File

@@ -1,6 +1,6 @@
// File: iteration.zig
// Created Time: 2023-09-27
// Author: QiLOL (pikaqqpika@gmail.com)
// Author: QiLOL (pikaqqpika@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const Allocator = std.mem.Allocator;
@@ -9,20 +9,19 @@ const Allocator = std.mem.Allocator;
fn forLoop(n: usize) i32 {
var res: i32 = 0;
// 循环求和 1, 2, ..., n-1, n
for (1..n+1) |i| {
res = res + @as(i32, @intCast(i));
for (1..n + 1) |i| {
res += @intCast(i);
}
return res;
}
}
// while 循环
fn whileLoop(n: i32) i32 {
var res: i32 = 0;
var i: i32 = 1; // 初始化条件变量
// 循环求和 1, 2, ..., n-1, n
while (i <= n) {
while (i <= n) : (i += 1) {
res += @intCast(i);
i += 1;
}
return res;
}
@@ -32,11 +31,12 @@ fn whileLoopII(n: i32) i32 {
var res: i32 = 0;
var i: i32 = 1; // 初始化条件变量
// 循环求和 1, 4, 10, ...
while (i <= n) {
res += @intCast(i);
while (i <= n) : ({
// 更新条件变量
i += 1;
i *= 2;
}) {
res += @intCast(i);
}
return res;
}
@@ -47,31 +47,45 @@ fn nestedForLoop(allocator: Allocator, n: usize) ![]const u8 {
defer res.deinit();
var buffer: [20]u8 = undefined;
// 循环 i = 1, 2, ..., n-1, n
for (1..n+1) |i| {
for (1..n + 1) |i| {
// 循环 j = 1, 2, ..., n-1, n
for (1..n+1) |j| {
var _str = try std.fmt.bufPrint(&buffer, "({d}, {d}), ", .{i, j});
try res.appendSlice(_str);
for (1..n + 1) |j| {
const str = try std.fmt.bufPrint(&buffer, "({d}, {d}), ", .{ i, j });
try res.appendSlice(str);
}
}
return res.toOwnedSlice();
}
// Driver Code
pub fn main() !void {
pub fn run() !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const n: i32 = 5;
var res: i32 = 0;
res = forLoop(n);
std.debug.print("\nfor 循环的求和结果 res = {}\n", .{res});
std.debug.print("for 循环的求和结果 res = {}\n", .{res});
res = whileLoop(n);
std.debug.print("\nwhile 循环的求和结果 res = {}\n", .{res});
std.debug.print("while 循环的求和结果 res = {}\n", .{res});
res = whileLoopII(n);
std.debug.print("\nwhile 循环(两次更新)求和结果 res = {}\n", .{res});
std.debug.print("while 循环(两次更新)求和结果 res = {}\n", .{res});
const allocator = std.heap.page_allocator;
const resStr = try nestedForLoop(allocator, n);
std.debug.print("\n双层 for 循环的遍历结果 {s}\n", .{resStr});
std.debug.print("双层 for 循环的遍历结果 {s}\n", .{resStr});
allocator.free(resStr);
std.debug.print("\n", .{});
}
pub fn main() !void {
try run();
}
test "interation" {
try run();
}

View File

@@ -1,7 +1,7 @@
// File: recursion.zig
// Created Time: 2023-09-27
// Author: QiLOL (pikaqqpika@gmail.com)
// Author: QiLOL (pikaqqpika@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
// 递归函数
@@ -11,7 +11,7 @@ fn recur(n: i32) i32 {
return 1;
}
// 递:递归调用
var res: i32 = recur(n - 1);
const res = recur(n - 1);
// 归:返回结果
return n + res;
}
@@ -54,25 +54,35 @@ fn fib(n: i32) i32 {
return n - 1;
}
// 递归调用 f(n) = f(n-1) + f(n-2)
var res: i32 = fib(n - 1) + fib(n - 2);
const res: i32 = fib(n - 1) + fib(n - 2);
// 返回结果 f(n)
return res;
}
// Driver Code
pub fn main() !void {
pub fn run() void {
const n: i32 = 5;
var res: i32 = 0;
res = recur(n);
std.debug.print("\n递归函数的求和结果 res = {}\n", .{recur(n)});
std.debug.print("递归函数的求和结果 res = {}\n", .{recur(n)});
res = forLoopRecur(n);
std.debug.print("\n使用迭代模拟递归的求和结果 res = {}\n", .{forLoopRecur(n)});
std.debug.print("使用迭代模拟递归的求和结果 res = {}\n", .{forLoopRecur(n)});
res = tailRecur(n, 0);
std.debug.print("\n尾递归函数的求和结果 res = {}\n", .{tailRecur(n, 0)});
std.debug.print("尾递归函数的求和结果 res = {}\n", .{tailRecur(n, 0)});
res = fib(n);
std.debug.print("\n斐波那契数列的第 {} 项为 {}\n", .{n, fib(n)});
std.debug.print("斐波那契数列的第 {} 项为 {}\n", .{ n, fib(n) });
std.debug.print("\n", .{});
}
pub fn main() void {
run();
}
test "recursion" {
run();
}

View File

@@ -1,9 +1,11 @@
// File: space_complexity.zig
// Created Time: 2023-01-07
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const inc = @import("include");
const utils = @import("utils");
const ListNode = utils.ListNode;
const TreeNode = utils.TreeNode;
// 函数
fn function() i32 {
@@ -15,13 +17,13 @@ fn function() i32 {
fn constant(n: i32) void {
// 常量、变量、对象占用 O(1) 空间
const a: i32 = 0;
var b: i32 = 0;
var nums = [_]i32{0}**10000;
var node = inc.ListNode(i32){.val = 0};
const b: i32 = 0;
const nums = [_]i32{0} ** 10000;
const node = ListNode(i32){ .val = 0 };
var i: i32 = 0;
// 循环中的变量占用 O(1) 空间
while (i < n) : (i += 1) {
var c: i32 = 0;
const c: i32 = 0;
_ = c;
}
// 循环中的函数占用 O(1) 空间
@@ -38,7 +40,7 @@ fn constant(n: i32) void {
// 线性阶
fn linear(comptime n: i32) !void {
// 长度为 n 的数组占用 O(n) 空间
var nums = [_]i32{0}**n;
const nums = [_]i32{0} ** n;
// 长度为 n 的列表占用 O(n) 空间
var nodes = std.ArrayList(i32).init(std.heap.page_allocator);
defer nodes.deinit();
@@ -85,23 +87,35 @@ fn quadratic(n: i32) !void {
// 平方阶(递归实现)
fn quadraticRecur(comptime n: i32) i32 {
if (n <= 0) return 0;
var nums = [_]i32{0}**n;
std.debug.print("递归 n = {} 中的 nums 长度 = {}\n", .{n, nums.len});
const nums = [_]i32{0} ** n;
std.debug.print("递归 n = {} 中的 nums 长度 = {}\n", .{ n, nums.len });
return quadraticRecur(n - 1);
}
// 指数阶(建立满二叉树)
fn buildTree(mem_allocator: std.mem.Allocator, n: i32) !?*inc.TreeNode(i32) {
fn buildTree(allocator: std.mem.Allocator, n: i32) !?*TreeNode(i32) {
if (n == 0) return null;
const root = try mem_allocator.create(inc.TreeNode(i32));
const root = try allocator.create(TreeNode(i32));
root.init(0);
root.left = try buildTree(mem_allocator, n - 1);
root.right = try buildTree(mem_allocator, n - 1);
root.left = try buildTree(allocator, n - 1);
root.right = try buildTree(allocator, n - 1);
return root;
}
// 释放树的内存
fn freeTree(allocator: std.mem.Allocator, root: ?*const TreeNode(i32)) void {
if (root == null) return;
freeTree(allocator, root.?.left);
freeTree(allocator, root.?.right);
allocator.destroy(root.?);
}
// Driver Code
pub fn main() !void {
pub fn run() !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const n: i32 = 5;
// 常数阶
constant(n);
@@ -112,13 +126,17 @@ pub fn main() !void {
try quadratic(n);
_ = quadraticRecur(n);
// 指数阶
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer mem_arena.deinit();
var root = blk_root: {
const mem_allocator = mem_arena.allocator();
break :blk_root try buildTree(mem_allocator, n);
};
try inc.PrintUtil.printTree(root, null, false);
const root = try buildTree(allocator, n);
defer freeTree(allocator, root);
std.debug.print("{}\n", .{utils.fmt.tree(i32, root)});
_ = try std.io.getStdIn().reader().readByte();
}
std.debug.print("\n", .{});
}
pub fn main() !void {
try run();
}
test "space_complexity" {
try run();
}

View File

@@ -1,6 +1,6 @@
// File: time_complexity.zig
// Created Time: 2022-12-28
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
@@ -10,7 +10,7 @@ fn constant(n: i32) i32 {
var count: i32 = 0;
const size: i32 = 100_000;
var i: i32 = 0;
while(i<size) : (i += 1) {
while (i < size) : (i += 1) {
count += 1;
}
return count;
@@ -52,7 +52,7 @@ fn quadratic(n: i32) i32 {
// 平方阶(冒泡排序)
fn bubbleSort(nums: []i32) i32 {
var count: i32 = 0; // 计数器
var count: i32 = 0; // 计数器
// 外循环:未排序区间为 [0, i]
var i: i32 = @as(i32, @intCast(nums.len)) - 1;
while (i > 0) : (i -= 1) {
@@ -61,10 +61,10 @@ fn bubbleSort(nums: []i32) i32 {
while (j < i) : (j += 1) {
if (nums[j] > nums[j + 1]) {
// 交换 nums[j] 与 nums[j + 1]
var tmp = nums[j];
const tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // 元素交换包含 3 个单元操作
count += 3; // 元素交换包含 3 个单元操作
}
}
}
@@ -97,11 +97,9 @@ fn expRecur(n: i32) i32 {
// 对数阶(循环实现)
fn logarithmic(n: i32) i32 {
var count: i32 = 0;
var n_var = n;
while (n_var > 1)
{
n_var = n_var / 2;
count +=1;
var n_var: i32 = n;
while (n_var > 1) : (n_var = @divTrunc(n_var, 2)) {
count += 1;
}
return count;
}
@@ -109,13 +107,13 @@ fn logarithmic(n: i32) i32 {
// 对数阶(递归实现)
fn logRecur(n: i32) i32 {
if (n <= 1) return 0;
return logRecur(n / 2) + 1;
return logRecur(@divTrunc(n, 2)) + 1;
}
// 线性对数阶
fn linearLogRecur(n: i32) i32 {
if (n <= 1) return 1;
var count: i32 = linearLogRecur(n / 2) + linearLogRecur(n / 2);
var count: i32 = linearLogRecur(@divTrunc(n, 2)) + linearLogRecur(@divTrunc(n, 2));
var i: i32 = 0;
while (i < n) : (i += 1) {
count += 1;
@@ -136,7 +134,7 @@ fn factorialRecur(n: i32) i32 {
}
// Driver Code
pub fn main() !void {
pub fn run() void {
// 可以修改 n 运行,体会一下各种复杂度的操作数量变化趋势
const n: i32 = 8;
std.debug.print("输入数据大小 n = {}\n", .{n});
@@ -146,14 +144,14 @@ pub fn main() !void {
count = linear(n);
std.debug.print("线性阶的操作数量 = {}\n", .{count});
var nums = [_]i32{0}**n;
var nums = [_]i32{0} ** n;
count = arrayTraversal(&nums);
std.debug.print("线性阶(遍历数组)的操作数量 = {}\n", .{count});
count = quadratic(n);
std.debug.print("平方阶的操作数量 = {}\n", .{count});
for (&nums, 0..) |*num, i| {
num.* = n - @as(i32, @intCast(i)); // [n,n-1,...,2,1]
num.* = n - @as(i32, @intCast(i)); // [n,n-1,...,2,1]
}
count = bubbleSort(&nums);
std.debug.print("平方阶(冒泡排序)的操作数量 = {}\n", .{count});
@@ -174,6 +172,13 @@ pub fn main() !void {
count = factorialRecur(n);
std.debug.print("阶乘阶(递归实现)的操作数量 = {}\n", .{count});
_ = try std.io.getStdIn().reader().readByte();
std.debug.print("\n", .{});
}
pub fn main() !void {
run();
}
test "time_complexity" {
run();
}

View File

@@ -1,9 +1,9 @@
// File: worst_best_time_complexity.zig
// Created Time: 2022-12-28
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const inc = @import("include");
const utils = @import("utils");
// 生成一个数组,元素为 { 1, 2, ..., n },顺序被打乱
pub fn randomNumbers(comptime n: usize) [n]i32 {
@@ -29,17 +29,25 @@ pub fn findOne(nums: []i32) i32 {
}
// Driver Code
pub fn main() !void {
pub fn run() void {
var i: i32 = 0;
while (i < 10) : (i += 1) {
const n: usize = 100;
var nums = randomNumbers(n);
var index = findOne(&nums);
std.debug.print("\n数组 [ 1, 2, ..., n ] 被打乱后 = ", .{});
inc.PrintUtil.printArray(i32, &nums);
const index = findOne(&nums);
std.debug.print("数组 [ 1, 2, ..., n ] 被打乱后 = ", .{});
std.debug.print("{}\n", .{utils.fmt.slice(nums)});
std.debug.print("数字 1 的索引为 {}\n", .{index});
}
_ = try std.io.getStdIn().reader().readByte();
std.debug.print("\n", .{});
}
pub fn main() !void {
run();
}
test "worst_best_time_complexity" {
run();
}

View File

@@ -8,45 +8,6 @@ pub const ListNode = ListUtil.ListNode;
pub const TreeUtil = @import("TreeNode.zig");
pub const TreeNode = TreeUtil.TreeNode;
// 打印数组
pub fn printArray(comptime T: type, nums: []T) void {
std.debug.print("[", .{});
if (nums.len > 0) {
for (nums, 0..) |num, j| {
std.debug.print("{}{s}", .{num, if (j == nums.len-1) "]" else ", " });
}
} else {
std.debug.print("]", .{});
}
}
// 打印列表
pub fn printList(comptime T: type, list: std.ArrayList(T)) void {
std.debug.print("[", .{});
if (list.items.len > 0) {
for (list.items, 0..) |value, i| {
std.debug.print("{}{s}", .{value, if (i == list.items.len-1) "]" else ", " });
}
} else {
std.debug.print("]", .{});
}
}
// 打印链表
pub fn printLinkedList(comptime T: type, node: ?*ListNode(T)) !void {
if (node == null) return;
var list = std.ArrayList(T).init(std.heap.page_allocator);
defer list.deinit();
var head = node;
while (head != null) {
try list.append(head.?.val);
head = head.?.next;
}
for (list.items, 0..) |value, i| {
std.debug.print("{}{s}", .{value, if (i == list.items.len-1) "\n" else "->" });
}
}
// 打印队列
pub fn printQueue(comptime T: type, queue: std.TailQueue(T)) void {
var node = queue.first;
@@ -54,7 +15,7 @@ pub fn printQueue(comptime T: type, queue: std.TailQueue(T)) void {
var i: i32 = 0;
while (node != null) : (i += 1) {
var data = node.?.data;
std.debug.print("{}{s}", .{data, if (i == queue.len - 1) "]" else ", " });
std.debug.print("{}{s}", .{ data, if (i == queue.len - 1) "]" else ", " });
node = node.?.next;
}
}
@@ -65,7 +26,7 @@ pub fn printHashMap(comptime TKey: type, comptime TValue: type, map: std.AutoHas
while (it.next()) |kv| {
var key = kv.key_ptr.*;
var value = kv.value_ptr.*;
std.debug.print("{} -> {s}\n", .{key, value});
std.debug.print("{} -> {s}\n", .{ key, value });
}
}
@@ -79,54 +40,3 @@ pub fn printHeap(comptime T: type, mem_allocator: std.mem.Allocator, queue: anyt
var root = try TreeUtil.arrToTree(T, mem_allocator, arr[0..len]);
try printTree(root, null, false);
}
// 打印二叉树
// This tree printer is borrowed from TECHIE DELIGHT
// https://www.techiedelight.com/c-program-print-binary-tree/
const Trunk = struct {
prev: ?*Trunk = null,
str: []const u8 = undefined,
pub fn init(self: *Trunk, prev: ?*Trunk, str: []const u8) void {
self.prev = prev;
self.str = str;
}
};
pub fn showTrunks(p: ?*Trunk) void {
if (p == null) return;
showTrunks(p.?.prev);
std.debug.print("{s}", .{p.?.str});
}
// 打印二叉树
pub fn printTree(root: ?*TreeNode(i32), prev: ?*Trunk, isRight: bool) !void {
if (root == null) {
return;
}
var prev_str = " ";
var trunk = Trunk{.prev = prev, .str = prev_str};
try printTree(root.?.right, &trunk, true);
if (prev == null) {
trunk.str = "———";
} else if (isRight) {
trunk.str = "/———";
prev_str = " |";
} else {
trunk.str = "\\———";
prev.?.str = prev_str;
}
showTrunks(&trunk);
std.debug.print(" {}\n", .{root.?.val});
if (prev) |_| {
prev.?.str = prev_str;
}
trunk.str = " |";
try printTree(root.?.left, &trunk, false);
}

View File

@@ -3,7 +3,5 @@
// Author: codingonion (coderonion@gmail.com)
pub const PrintUtil = @import("PrintUtil.zig");
pub const ListUtil = @import("ListNode.zig");
pub const ListNode = ListUtil.ListNode;
pub const TreeUtil = @import("TreeNode.zig");
pub const TreeNode = TreeUtil.TreeNode;
pub const TreeNode = TreeUtil.TreeNode;

25
codes/zig/main.zig Normal file
View File

@@ -0,0 +1,25 @@
const std = @import("std");
const iteration = @import("chapter_computational_complexity/iteration.zig");
const recursion = @import("chapter_computational_complexity/recursion.zig");
const time_complexity = @import("chapter_computational_complexity/time_complexity.zig");
const space_complexity = @import("chapter_computational_complexity/space_complexity.zig");
const worst_best_time_complexity = @import("chapter_computational_complexity/worst_best_time_complexity.zig");
const array = @import("chapter_array_and_linkedlist/array.zig");
const linked_list = @import("chapter_array_and_linkedlist/linked_list.zig");
const list = @import("chapter_array_and_linkedlist/list.zig");
const my_list = @import("chapter_array_and_linkedlist/my_list.zig");
pub fn main() !void {
try iteration.run();
recursion.run();
time_complexity.run();
try space_complexity.run();
worst_best_time_complexity.run();
try array.run();
linked_list.run();
try list.run();
try my_list.run();
}

View File

@@ -1,6 +1,6 @@
// File: ListNode.zig
// Created Time: 2023-01-07
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
@@ -8,7 +8,7 @@ const std = @import("std");
pub fn ListNode(comptime T: type) type {
return struct {
const Self = @This();
val: T = 0,
next: ?*Self = null,
@@ -21,12 +21,12 @@ pub fn ListNode(comptime T: type) type {
}
//
pub fn listToLinkedList(comptime T: type, mem_allocator: std.mem.Allocator, list: std.ArrayList(T)) !?*ListNode(T) {
var dum = try mem_allocator.create(ListNode(T));
pub fn listToLinkedList(comptime T: type, allocator: std.mem.Allocator, list: std.ArrayList(T)) !?*ListNode(T) {
var dum = try allocator.create(ListNode(T));
dum.init(0);
var head = dum;
for (list.items) |val| {
var tmp = try mem_allocator.create(ListNode(T));
var tmp = try allocator.create(ListNode(T));
tmp.init(val);
head.next = tmp;
head = head.next.?;
@@ -46,4 +46,4 @@ pub fn arrToLinkedList(comptime T: type, mem_allocator: std.mem.Allocator, arr:
head = head.next.?;
}
return dum.next;
}
}

View File

@@ -1,6 +1,6 @@
// File: TreeNode.zig
// Created Time: 2023-01-07
// Author: codingonion (coderonion@gmail.com)
// Author: codingonion (coderonion@gmail.com), CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
@@ -9,10 +9,10 @@ pub fn TreeNode(comptime T: type) type {
return struct {
const Self = @This();
val: T = undefined, //
height: i32 = undefined, //
left: ?*Self = null, //
right: ?*Self = null, //
val: T = undefined, //
height: i32 = undefined, //
left: ?*Self = null, //
right: ?*Self = null, //
// Initialize a tree node with specific value
pub fn init(self: *Self, x: i32) void {
@@ -21,43 +21,43 @@ pub fn TreeNode(comptime T: type) type {
self.left = null;
self.right = null;
}
};
};
}
//
pub fn arrToTree(comptime T: type, mem_allocator: std.mem.Allocator, arr: []T) !?*TreeNode(T) {
pub fn arrToTree(comptime T: type, allocator: std.mem.Allocator, arr: []T) !?*TreeNode(T) {
if (arr.len == 0) return null;
var root = try mem_allocator.create(TreeNode(T));
var root = try allocator.create(TreeNode(T));
root.init(arr[0]);
const L = std.TailQueue(*TreeNode(T));
var que = L{};
var root_node = try mem_allocator.create(L.Node);
var root_node = try allocator.create(L.Node);
root_node.data = root;
que.append(root_node);
que.append(root_node);
var index: usize = 0;
while (que.len > 0) {
var que_node = que.popFirst().?;
const que_node = que.popFirst().?;
var node = que_node.data;
index += 1;
if (index >= arr.len) break;
if (index < arr.len) {
var tmp = try mem_allocator.create(TreeNode(T));
var tmp = try allocator.create(TreeNode(T));
tmp.init(arr[index]);
node.left = tmp;
var tmp_node = try mem_allocator.create(L.Node);
var tmp_node = try allocator.create(L.Node);
tmp_node.data = node.left.?;
que.append(tmp_node);
}
index += 1;
if (index >= arr.len) break;
if (index < arr.len) {
var tmp = try mem_allocator.create(TreeNode(T));
var tmp = try allocator.create(TreeNode(T));
tmp.init(arr[index]);
node.right = tmp;
var tmp_node = try mem_allocator.create(L.Node);
var tmp_node = try allocator.create(L.Node);
tmp_node.data = node.right.?;
que.append(tmp_node);
}
}
return root;
}
}

140
codes/zig/utils/format.zig Normal file
View File

@@ -0,0 +1,140 @@
// File: format.zig
// Created Time: 2025-07-19
// Author: CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
const ListNode = @import("ListNode.zig").ListNode;
const TreeNode = @import("TreeNode.zig").TreeNode;
pub fn slice(items: anytype) SliceFormatter(@TypeOf(items)) {
return .{ .items = items };
}
pub fn SliceFormatter(comptime SliceType: type) type {
return struct {
const Self = @This();
items: SliceType,
pub fn format(
self: Self,
comptime _: []const u8,
_: std.fmt.FormatOptions,
writer: anytype,
) !void {
try writer.writeAll("[");
if (self.items.len > 0) {
for (self.items, 0..) |item, i| {
try std.fmt.format(writer, "{}", .{item});
if (i != self.items.len - 1) {
try writer.writeAll(", ");
}
}
}
try writer.writeAll("]");
}
};
}
pub fn linkedList(comptime T: type, head: *const ListNode(T)) LinkedListFormatter(T) {
return .{ .head = head };
}
pub fn LinkedListFormatter(comptime T: type) type {
return struct {
const Self = @This();
head: *const ListNode(T),
pub fn format(
self: Self,
comptime _: []const u8,
_: std.fmt.FormatOptions,
writer: anytype,
) !void {
try printLinkedList(self.head, writer);
}
pub fn printLinkedList(head: *const ListNode(T), writer: anytype) !void {
try std.fmt.format(writer, "{}", .{head.val});
if (head.next) |next_node| {
try writer.writeAll("->");
try printLinkedList(next_node, writer);
}
}
};
}
pub fn tree(comptime T: type, root: ?*const TreeNode(T)) TreeFormatter(T) {
return .{ .root = root };
}
pub fn TreeFormatter(comptime T: type) type {
return struct {
const Self = @This();
root: ?*const TreeNode(T),
pub fn format(
self: Self,
comptime _: []const u8,
_: std.fmt.FormatOptions,
writer: anytype,
) !void {
try printTree(self.root, null, false, writer);
}
// 打印二叉树
fn printTree(root: ?*const TreeNode(T), prev: ?*Trunk, isRight: bool, writer: anytype) !void {
if (root == null) {
return;
}
var prev_str = " ";
var trunk = Trunk{ .prev = prev, .str = prev_str };
try printTree(root.?.right, &trunk, true, writer);
if (prev == null) {
trunk.str = "———";
} else if (isRight) {
trunk.str = "/———";
prev_str = " |";
} else {
trunk.str = "\\———";
prev.?.str = prev_str;
}
try showTrunks(&trunk, writer);
try std.fmt.format(writer, "{d}\n", .{root.?.val});
if (prev) |_| {
prev.?.str = prev_str;
}
trunk.str = " |";
try printTree(root.?.left, &trunk, false, writer);
}
// 打印二叉树
// This tree printer is borrowed from TECHIE DELIGHT
// https://www.techiedelight.com/c-program-print-binary-tree/
const Trunk = struct {
prev: ?*Trunk = null,
str: []const u8 = undefined,
pub fn init(self: *Trunk, prev: ?*Trunk, str: []const u8) void {
self.prev = prev;
self.str = str;
}
};
pub fn showTrunks(p: ?*Trunk, writer: anytype) !void {
if (p == null) return;
try showTrunks(p.?.prev, writer);
try std.fmt.format(writer, "{s}", .{p.?.str});
}
};
}

View File

@@ -0,0 +1,8 @@
// File: format.zig
// Created Time: 2025-07-15
// Author: CreatorMetaSky (creator_meta_sky@163.com)
const std = @import("std");
pub const fmt = @import("format.zig");
pub const ListNode = @import("ListNode.zig").ListNode;
pub const TreeNode = @import("TreeNode.zig").TreeNode;

View File

@@ -15,7 +15,7 @@
```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++"
@@ -130,8 +130,8 @@
```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 "可视化运行"