mirror of
https://github.com/krahets/hello-algo.git
synced 2025-12-19 07:17:54 +08:00
add zig codes for Section 'Hash Map', 'Linear Search' and 'Heap'
This commit is contained in:
@@ -3,8 +3,10 @@
|
||||
// Author: sjinzh (sjinzh@gmail.com)
|
||||
|
||||
const std = @import("std");
|
||||
const ListNode = @import("ListNode.zig").ListNode;
|
||||
const TreeNode = @import("TreeNode.zig").TreeNode;
|
||||
pub const ListUtil = @import("ListNode.zig");
|
||||
pub const ListNode = ListUtil.ListNode;
|
||||
pub const TreeUtil = @import("TreeNode.zig");
|
||||
pub const TreeNode = TreeUtil.TreeNode;
|
||||
|
||||
// Print an array
|
||||
pub fn printArray(comptime T: type, nums: []T) void {
|
||||
@@ -56,6 +58,17 @@ pub fn printHashMap(comptime TKey: type, comptime TValue: type, map: std.AutoHas
|
||||
}
|
||||
}
|
||||
|
||||
// print a heap (PriorityQueue)
|
||||
pub fn printHeap(comptime T: type, mem_allocator: std.mem.Allocator, queue: anytype) !void {
|
||||
var arr = queue.items;
|
||||
var len = queue.len;
|
||||
std.debug.print("堆的数组表示:", .{});
|
||||
printArray(T, arr[0..len]);
|
||||
std.debug.print("\n堆的树状表示:\n", .{});
|
||||
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 {
|
||||
|
||||
@@ -21,4 +21,40 @@ pub fn TreeNode(comptime T: type) type {
|
||||
self.right = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Generate a binary tree with an array
|
||||
pub fn arrToTree(comptime T: type, mem_allocator: std.mem.Allocator, list: []T) !?*TreeNode(T) {
|
||||
if (list.len == 0) return null;
|
||||
var root = try mem_allocator.create(TreeNode(T));
|
||||
root.init(list[0]);
|
||||
|
||||
const TailQueue = std.TailQueue(?*TreeNode(T));
|
||||
const TailQueueNode = std.TailQueue(?*TreeNode(T)).Node;
|
||||
var que = TailQueue{};
|
||||
var node_root = TailQueueNode{ .data = root };
|
||||
que.append(&node_root);
|
||||
var index: usize = 0;
|
||||
while (que.len > 0) {
|
||||
var node = que.popFirst();
|
||||
index += 1;
|
||||
if (index >= list.len) break;
|
||||
if (index < list.len) {
|
||||
var tmp = try mem_allocator.create(TreeNode(T));
|
||||
tmp.init(list[index]);
|
||||
node.?.data.?.left = tmp;
|
||||
var a = TailQueueNode{ .data = node.?.data.?.left };
|
||||
que.append(&a);
|
||||
}
|
||||
index += 1;
|
||||
if (index >= list.len) break;
|
||||
if (index < list.len) {
|
||||
var tmp = try mem_allocator.create(TreeNode(T));
|
||||
tmp.init(list[index]);
|
||||
node.?.data.?.right = tmp;
|
||||
var a = TailQueueNode{ .data = node.?.data.?.right };
|
||||
que.append(&a);
|
||||
}
|
||||
}
|
||||
return root;
|
||||
}
|
||||
Reference in New Issue
Block a user