Merge pull request #237 from sjinzh/master

add zig codes for Section 'Array', 'LinkedList' and  'List'
This commit is contained in:
Yudong Jin
2023-01-12 20:31:47 +08:00
committed by GitHub
6 changed files with 544 additions and 3 deletions

View File

@ -64,4 +64,59 @@ pub fn build(b: *std.build.Builder) void {
if (b.args) |args| run_cmd_leetcode_two_sum.addArgs(args);
const run_step_leetcode_two_sum = b.step("run_leetcode_two_sum", "Run leetcode_two_sum");
run_step_leetcode_two_sum.dependOn(&run_cmd_leetcode_two_sum.step);
// Section: "Array"
// Source File: "chapter_array_and_linkedlist/array.zig"
// Run Command: zig build run_array
const exe_array = b.addExecutable("array", "chapter_array_and_linkedlist/array.zig");
exe_array.addPackagePath("include", "include/include.zig");
exe_array.setTarget(target);
exe_array.setBuildMode(mode);
exe_array.install();
const run_cmd_array = exe_array.run();
run_cmd_array.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_array.addArgs(args);
const run_step_array = b.step("run_array", "Run array");
run_step_array.dependOn(&run_cmd_array.step);
// Section: "LinkedList"
// Source File: "chapter_array_and_linkedlist/linked_list.zig"
// Run Command: zig build run_linked_list
const exe_linked_list = b.addExecutable("linked_list", "chapter_array_and_linkedlist/linked_list.zig");
exe_linked_list.addPackagePath("include", "include/include.zig");
exe_linked_list.setTarget(target);
exe_linked_list.setBuildMode(mode);
exe_linked_list.install();
const run_cmd_linked_list = exe_linked_list.run();
run_cmd_linked_list.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_linked_list.addArgs(args);
const run_step_linked_list = b.step("run_linked_list", "Run linked_list");
run_step_linked_list.dependOn(&run_cmd_linked_list.step);
// Section: "List"
// Source File: "chapter_array_and_linkedlist/list.zig"
// Run Command: zig build run_list
const exe_list = b.addExecutable("list", "chapter_array_and_linkedlist/list.zig");
exe_list.addPackagePath("include", "include/include.zig");
exe_list.setTarget(target);
exe_list.setBuildMode(mode);
exe_list.install();
const run_cmd_list = exe_list.run();
run_cmd_list.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_list.addArgs(args);
const run_step_list = b.step("run_list", "Run list");
run_step_list.dependOn(&run_cmd_list.step);
// Source File: "chapter_array_and_linkedlist/my_list.zig"
// Run Command: zig build run_my_list
const exe_my_list = b.addExecutable("my_list", "chapter_array_and_linkedlist/my_list.zig");
exe_my_list.addPackagePath("include", "include/include.zig");
exe_my_list.setTarget(target);
exe_my_list.setBuildMode(mode);
exe_my_list.install();
const run_cmd_my_list = exe_my_list.run();
run_cmd_my_list.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_my_list.addArgs(args);
const run_step_my_list = b.step("run_my_list", "Run my_list");
run_step_my_list.dependOn(&run_cmd_my_list.step);
}

View File

@ -0,0 +1,117 @@
// File: array.zig
// Created Time: 2023-01-07
// Author: sjinzh (sjinzh@gmail.com)
const std = @import("std");
const inc = @import("include");
// 随机返回一个数组元素
pub fn randomAccess(nums: []i32) i32 {
// 在区间 [0, nums.len) 中随机抽取一个整数
var randomIndex = std.crypto.random.intRangeLessThan(usize, 0, nums.len);
// 获取并返回随机元素
var randomNum = nums[randomIndex];
return randomNum;
}
// 扩展数组长度
pub fn extend(mem_allocator: std.mem.Allocator, nums: []i32, enlarge: usize) ![]i32 {
// 初始化一个扩展长度后的数组
var res = try mem_allocator.alloc(i32, nums.len + enlarge);
std.mem.set(i32, res, 0);
// 将原数组中的所有元素复制到新数组
std.mem.copy(i32, res, nums);
// 返回扩展后的新数组
return res;
}
// 在数组的索引 index 处插入元素 num
pub fn insert(nums: []i32, num: i32, index: usize) void {
// 把索引 index 以及之后的所有元素向后移动一位
var i = nums.len - 1;
while (i > index) : (i -= 1) {
nums[i] = nums[i - 1];
}
// 将 num 赋给 index 处元素
nums[index] = num;
}
// 删除索引 index 处元素
pub fn remove(nums: []i32, index: usize) void {
// 把索引 index 之后的所有元素向前移动一位
var i = index;
while (i < nums.len - 1) : (i += 1) {
nums[i] = nums[i + 1];
}
}
// 遍历数组
pub fn traverse(nums: []i32) void {
var count: i32 = 0;
// 通过索引遍历数组
var i: i32 = 0;
while (i < nums.len) : (i += 1) {
count += 1;
}
count = 0;
// 直接遍历数组
for (nums) |_| {
count += 1;
}
}
// 在数组中查找指定元素
pub fn find(nums: []i32, target: i32) i32 {
for (nums) |num, i| {
if (num == target) return @intCast(i32, i);
}
return -1;
}
// Driver Code
pub fn main() !void {
// 初始化数组
const size: i32 = 5;
var arr = [_]i32{0} ** size;
std.debug.print("数组 arr = ", .{});
inc.PrintUtil.printArray(i32, &arr);
var array = [_]i32{ 1, 3, 2, 5, 4 };
std.debug.print("\n数组 nums = ", .{});
inc.PrintUtil.printArray(i32, &array);
// 随机访问
var randomNum = randomAccess(&array);
std.debug.print("\n在 nums 中获取随机元素 {}", .{randomNum});
// 长度扩展
var known_at_runtime_zero: usize = 0;
var nums: []i32 = array[known_at_runtime_zero..array.len];
var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer mem_arena.deinit();
const mem_allocator = mem_arena.allocator();
nums = try extend(mem_allocator, nums, 3);
std.debug.print("\n将数组长度扩展至 8 ,得到 nums = ", .{});
inc.PrintUtil.printArray(i32, nums);
// 插入元素
insert(nums, 6, 3);
std.debug.print("\n在索引 3 处插入数字 6 ,得到 nums = ", .{});
inc.PrintUtil.printArray(i32, nums);
// 删除元素
remove(nums, 2);
std.debug.print("\n删除索引 2 处的元素,得到 nums = ", .{});
inc.PrintUtil.printArray(i32, nums);
// 遍历数组
traverse(nums);
// 查找元素
var index = find(nums, 3);
std.debug.print("\n在 nums 中查找元素 3 ,得到索引 = {}\n", .{index});
const getchar = try std.io.getStdIn().reader().readByte();
_ = getchar;
}

View File

@ -0,0 +1,85 @@
// File: linked_list.zig
// Created Time: 2023-01-07
// Author: sjinzh (sjinzh@gmail.com)
const std = @import("std");
const inc = @import("include");
// 在链表的结点 n0 之后插入结点 P
pub fn insert(n0: ?*inc.ListNode(i32), P: ?*inc.ListNode(i32)) void {
var n1 = n0.?.next;
n0.?.next = P;
P.?.next = n1;
}
// 删除链表的结点 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;
}
// 访问链表中索引为 index 的结点
pub fn access(node: ?*inc.ListNode(i32), index: i32) ?*inc.ListNode(i32) {
var head = node;
var i: i32 = 0;
while (i < index) : (i += 1) {
head = head.?.next;
if (head == null) return null;
}
return head;
}
// 在链表中查找值为 target 的首个结点
pub fn find(node: ?*inc.ListNode(i32), target: i32) i32 {
var head = node;
var index: i32 = 0;
while (head != null) {
if (head.?.val == target) return index;
head = head.?.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};
// 构建引用指向
n0.next = &n1;
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
std.debug.print("初始化的链表为", .{});
try inc.PrintUtil.printLinkedList(i32, &n0);
// 插入结点
var tmp = inc.ListNode(i32){.val = 0};
insert(&n0, &tmp);
std.debug.print("插入结点后的链表为", .{});
try inc.PrintUtil.printLinkedList(i32, &n0);
// 删除结点
remove(&n0);
std.debug.print("删除结点后的链表为", .{});
try inc.PrintUtil.printLinkedList(i32, &n0);
// 访问结点
var node = access(&n0, 3);
std.debug.print("链表中索引 3 处的结点的值 = {}\n", .{node.?.val});
// 查找结点
var index = find(&n0, 2);
std.debug.print("链表中值为 2 的结点的索引 = {}\n", .{index});
const getchar = try std.io.getStdIn().reader().readByte();
_ = getchar;
}

View File

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

View File

@ -0,0 +1,177 @@
// File: my_list.zig
// Created Time: 2023-01-08
// Author: sjinzh (sjinzh@gmail.com)
const std = @import("std");
const inc = @import("include");
// 列表类简易实现
// 编译期泛型
pub fn MyList(comptime T: type) type {
return struct {
const Self = @This();
nums: []T = undefined, // 数组(存储列表元素)
numsCapacity: usize = 10, // 列表容量
numSize: usize = 0, // 列表长度(即当前元素数量)
extendRatio: usize = 2, // 每次列表扩容的倍数
mem_arena: ?std.heap.ArenaAllocator = null,
mem_allocator: std.mem.Allocator = undefined, // 内存分配器
// 构造函数(分配内存+初始化列表)
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.nums = try self.mem_allocator.alloc(T, self.numsCapacity);
std.mem.set(T, self.nums, @as(T, 0));
}
// 析构函数(释放内存)
pub fn deinit(self: *Self) void {
if (self.mem_arena == null) return;
self.mem_arena.?.deinit();
}
// 获取列表长度(即当前元素数量)
pub fn size(self: *Self) usize {
return self.numSize;
}
// 获取列表容量
pub fn capacity(self: *Self) usize {
return self.numsCapacity;
}
// 访问元素
pub fn get(self: *Self, index: usize) T {
// 索引如果越界则抛出异常,下同
if (index >= self.size()) @panic("索引越界");
return self.nums[index];
}
// 更新元素
pub fn set(self: *Self, index: usize, num: T) void {
// 索引如果越界则抛出异常,下同
if (index >= self.size()) @panic("索引越界");
self.nums[index] = num;
}
// 尾部添加元素
pub fn add(self: *Self, num: T) !void {
// 元素数量超出容量时,触发扩容机制
if (self.size() == self.capacity()) try self.extendCapacity();
self.nums[self.size()] = num;
// 更新元素数量
self.numSize += 1;
}
// 中间插入元素
pub fn insert(self: *Self, index: usize, num: T) !void {
if (index >= self.size()) @panic("索引越界");
// 元素数量超出容量时,触发扩容机制
if (self.size() == self.capacity()) try self.extendCapacity();
// 索引 i 以及之后的元素都向后移动一位
var j = self.size() - 1;
while (j >= index) : (j -= 1) {
self.nums[j + 1] = self.nums[j];
}
self.nums[index] = num;
// 更新元素数量
self.numSize += 1;
}
// 删除元素
pub fn remove(self: *Self, index: usize) T {
if (index >= self.size()) @panic("索引越界");
var num = self.nums[index];
// 索引 i 之后的元素都向前移动一位
var j = index;
while (j < self.size() - 1) : (j += 1) {
self.nums[j] = self.nums[j + 1];
}
// 更新元素数量
self.numSize -= 1;
// 返回被删除元素
return num;
}
// 列表扩容
pub fn extendCapacity(self: *Self) !void {
// 新建一个长度为 size * extendRatio 的数组,并将原数组拷贝到新数组
var newCapacity = self.capacity() * self.extendRatio;
var extend = try self.mem_allocator.alloc(T, newCapacity);
std.mem.set(T, extend, @as(T, 0));
// 将原数组中的所有元素复制到新数组
std.mem.copy(T, extend, self.nums);
self.nums = extend;
// 更新列表容量
self.numsCapacity = newCapacity;
}
// 将列表转换为数组
pub fn toArray(self: *Self) ![]T {
// 仅转换有效长度范围内的列表元素
var nums = try self.mem_allocator.alloc(T, self.size());
std.mem.set(T, nums, @as(T, 0));
for (nums) |*num, i| {
num.* = self.get(i);
}
return nums;
}
};
}
// Driver Code
pub fn main() !void {
// 初始化列表
var list = MyList(i32){};
try list.init(std.heap.page_allocator);
// 延迟释放内存
defer list.deinit();
// 尾部添加元素
try list.add(1);
try list.add(3);
try list.add(2);
try list.add(5);
try list.add(4);
std.debug.print("列表 list = ", .{});
inc.PrintUtil.printArray(i32, try list.toArray());
std.debug.print(" ,容量 = {} ,长度 = {}", .{list.capacity(), list.size()});
// 中间插入元素
try list.insert(3, 6);
std.debug.print("\n在索引 3 处插入数字 6 ,得到 list = ", .{});
inc.PrintUtil.printArray(i32, try list.toArray());
// 删除元素
_ = list.remove(3);
std.debug.print("\n删除索引 3 处的元素,得到 list = ", .{});
inc.PrintUtil.printArray(i32, try list.toArray());
// 访问元素
var num = list.get(1);
std.debug.print("\n访问索引 1 处的元素,得到 num = {}", .{num});
// 更新元素
list.set(1, 0);
std.debug.print("\n将索引 1 处的元素更新为 0 ,得到 list = ", .{});
inc.PrintUtil.printArray(i32, try list.toArray());
// 测试扩容机制
list.set(1, 0);
var i: i32 = 0;
while (i < 10) : (i += 1) {
// 在 i = 5 时,列表长度将超出列表容量,此时触发扩容机制
try list.add(i);
}
std.debug.print("\n扩容后的列表 list = ", .{});
inc.PrintUtil.printArray(i32, try list.toArray());
std.debug.print(" ,容量 = {} ,长度 = {}\n", .{list.capacity(), list.size()});
const getchar = try std.io.getStdIn().reader().readByte();
_ = getchar;
}

View File

@ -7,16 +7,42 @@ const ListNode = @import("ListNode.zig").ListNode;
const TreeNode = @import("TreeNode.zig").TreeNode;
// Print an array
// 编译期泛型
pub fn printArray(comptime T: type, nums: []T) void {
std.debug.print("[", .{});
if (nums.len > 0) {
for (nums) |num, j| {
std.debug.print("{}{s}", .{num, if (j == nums.len-1) "]\n" else ", " });
std.debug.print("{}{s}", .{num, if (j == nums.len-1) "]" else ", " });
}
} else {
std.debug.print("]", .{});
std.debug.print("\n", .{});
}
}
// Print a list
pub fn printList(comptime T: type, list: std.ArrayList(T)) void {
std.debug.print("[", .{});
if (list.items.len > 0) {
for (list.items) |value, i| {
std.debug.print("{}{s}", .{value, if (i == list.items.len-1) "]" else ", " });
}
} else {
std.debug.print("]", .{});
}
}
// Print a linked list
pub fn printLinkedList(comptime T: type, node: ?*ListNode(T)) !void {
if (node == null) return;
var list = std.ArrayList(i32).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) |value, i| {
std.debug.print("{}{s}", .{value, if (i == list.items.len-1) "\n" else "->" });
}
}