Fix bugs and harmonize the code comments (#1199)

* Fix the comment in array_deque.go

* Fix the comment in bucket_sort.c

* Translate the Java code comments to Chinese

* Bug fixes

* 二分查找 -> 二分搜尋

* Harmonize comments in `utils` between multiple programming languages
This commit is contained in:
Yudong Jin 2024-03-31 03:06:41 +08:00 committed by GitHub
parent cfe8281aee
commit 034ee65e9a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
35 changed files with 133 additions and 271 deletions

View File

@ -6,7 +6,7 @@
#include "../utils/common.h" #include "../utils/common.h"
#define ARRAY_SIZE 10 #define SIZE 10
/* 比较两个浮点数的大小 */ /* 比较两个浮点数的大小 */
int compare_float(const void *a, const void *b) { int compare_float(const void *a, const void *b) {
@ -28,8 +28,8 @@ void bucketSort(float nums[], int size) {
int k = size / 2; int k = size / 2;
float **buckets = calloc(k, sizeof(float *)); float **buckets = calloc(k, sizeof(float *));
for (int i = 0; i < k; i++) { for (int i = 0; i < k; i++) {
// 每个桶最多可以分配 k 个元素 // 每个桶最多可以分配 size 个元素
buckets[i] = calloc(ARRAY_SIZE, sizeof(float)); buckets[i] = calloc(size, sizeof(float));
} }
// 1. 将数组元素分配到各个桶中 // 1. 将数组元素分配到各个桶中
@ -42,7 +42,7 @@ void bucketSort(float nums[], int size) {
j++; j++;
} }
float temp = nums[i]; float temp = nums[i];
while (j < ARRAY_SIZE && buckets[bucket_idx][j] > 0) { while (j < size && buckets[bucket_idx][j] > 0) {
swap(&temp, &buckets[bucket_idx][j]); swap(&temp, &buckets[bucket_idx][j]);
j++; j++;
} }
@ -51,12 +51,12 @@ void bucketSort(float nums[], int size) {
// 2. 对各个桶执行排序 // 2. 对各个桶执行排序
for (int i = 0; i < k; i++) { for (int i = 0; i < k; i++) {
qsort(buckets[i], ARRAY_SIZE, sizeof(float), compare_float); qsort(buckets[i], size, sizeof(float), compare_float);
} }
// 3. 遍历桶合并结果 // 3. 遍历桶合并结果
for (int i = 0, j = 0; j < k; j++) { for (int i = 0, j = 0; j < k; j++) {
for (int l = 0; l < ARRAY_SIZE; l++) { for (int l = 0; l < size; l++) {
if (buckets[j][l] > 0) { if (buckets[j][l] > 0) {
nums[i++] = buckets[j][l]; nums[i++] = buckets[j][l];
} }
@ -73,10 +73,10 @@ void bucketSort(float nums[], int size) {
/* Driver Code */ /* Driver Code */
int main() { int main() {
// 设输入数据为浮点数,范围为 [0, 1) // 设输入数据为浮点数,范围为 [0, 1)
float nums[ARRAY_SIZE] = {0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f}; float nums[SIZE] = {0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f};
bucketSort(nums, ARRAY_SIZE); bucketSort(nums, SIZE);
printf("桶排序完成后 nums = "); printf("桶排序完成后 nums = ");
printArrayFloat(nums, ARRAY_SIZE); printArrayFloat(nums, SIZE);
return 0; return 0;
} }

View File

@ -11,9 +11,6 @@ void testListNode() {
int size = sizeof(nums) / sizeof(int); int size = sizeof(nums) / sizeof(int);
ListNode *head = arrToLinkedList(nums, size); ListNode *head = arrToLinkedList(nums, size);
printLinkedList(head); printLinkedList(head);
ListNode *node = getListNode(head, 5);
printf("find node: %d\n", node->val);
} }
void testTreeNode() { void testTreeNode() {

View File

@ -26,7 +26,7 @@ ListNode *newListNode(int val) {
return node; return node;
} }
/* Generate a linked list with an array */ /* 将数组反序列化为链表 */
ListNode *arrToLinkedList(const int *arr, size_t size) { ListNode *arrToLinkedList(const int *arr, size_t size) {
if (size <= 0) { if (size <= 0) {
return NULL; return NULL;
@ -41,15 +41,7 @@ ListNode *arrToLinkedList(const int *arr, size_t size) {
return dummy->next; return dummy->next;
} }
/* Get a list node with specific value from a linked list */ /* 释放分配给链表的内存空间 */
ListNode *getListNode(ListNode *head, int val) {
while (head != NULL && head->val != val) {
head = head->next;
}
return head;
}
/* Free the memory allocated to a linked list */
void freeMemoryLinkedList(ListNode *cur) { void freeMemoryLinkedList(ListNode *cur) {
// 释放内存 // 释放内存
ListNode *pre; ListNode *pre;

View File

@ -18,7 +18,7 @@
extern "C" { extern "C" {
#endif #endif
/* Print an Array */ /* 打印数组 */
void printArray(int arr[], int size) { void printArray(int arr[], int size) {
if (arr == NULL || size == 0) { if (arr == NULL || size == 0) {
printf("[]"); printf("[]");
@ -31,7 +31,7 @@ void printArray(int arr[], int size) {
printf("%d]\n", arr[size - 1]); printf("%d]\n", arr[size - 1]);
} }
/* Print an Array */ /* 打印数组 */
void printArrayFloat(float arr[], int size) { void printArrayFloat(float arr[], int size) {
if (arr == NULL || size == 0) { if (arr == NULL || size == 0) {
printf("[]"); printf("[]");
@ -44,7 +44,7 @@ void printArrayFloat(float arr[], int size) {
printf("%.2f]\n", arr[size - 1]); printf("%.2f]\n", arr[size - 1]);
} }
/* Print a linked list */ /* 打印链表 */
void printLinkedList(ListNode *node) { void printLinkedList(ListNode *node) {
if (node == NULL) { if (node == NULL) {
return; return;
@ -69,7 +69,6 @@ Trunk *newTrunk(Trunk *prev, char *str) {
return trunk; return trunk;
} }
/* Helper function to print branches of the binary tree */
void showTrunks(Trunk *trunk) { void showTrunks(Trunk *trunk) {
if (trunk == NULL) { if (trunk == NULL) {
return; return;
@ -78,7 +77,11 @@ void showTrunks(Trunk *trunk) {
printf("%s", trunk->str); printf("%s", trunk->str);
} }
/* Help to print a binary tree, hide more details */ /**
*
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
void printTreeHelper(TreeNode *node, Trunk *prev, bool isRight) { void printTreeHelper(TreeNode *node, Trunk *prev, bool isRight) {
if (node == NULL) { if (node == NULL) {
return; return;
@ -106,12 +109,12 @@ void printTreeHelper(TreeNode *node, Trunk *prev, bool isRight) {
printTreeHelper(node->left, trunk, false); printTreeHelper(node->left, trunk, false);
} }
/* Print a binary tree */ /* 打印二叉树 */
void printTree(TreeNode *root) { void printTree(TreeNode *root) {
printTreeHelper(root, NULL, false); printTreeHelper(root, NULL, false);
} }
/* Print a Heap */ /* 打印堆 */
void printHeap(int arr[], int size) { void printHeap(int arr[], int size) {
TreeNode *root; TreeNode *root;
printf("堆的数组表示:"); printf("堆的数组表示:");

View File

@ -11,7 +11,7 @@
using namespace std; using namespace std;
/* Definition for a singly-linked list node */ /* 链表节点 */
struct ListNode { struct ListNode {
int val; int val;
ListNode *next; ListNode *next;
@ -19,7 +19,7 @@ struct ListNode {
} }
}; };
/* Generate a linked list with a vector */ /* 将列表反序列化为链表 */
ListNode *vecToLinkedList(vector<int> list) { ListNode *vecToLinkedList(vector<int> list) {
ListNode *dum = new ListNode(0); ListNode *dum = new ListNode(0);
ListNode *head = dum; ListNode *head = dum;
@ -30,15 +30,7 @@ ListNode *vecToLinkedList(vector<int> list) {
return dum->next; return dum->next;
} }
/* Get a list node with specific value from a linked list */ /* 释放分配给链表的内存空间 */
ListNode *getListNode(ListNode *head, int val) {
while (head != nullptr && head->val != val) {
head = head->next;
}
return head;
}
/* Free the memory allocated to a linked list */
void freeMemoryLinkedList(ListNode *cur) { void freeMemoryLinkedList(ListNode *cur) {
// 释放内存 // 释放内存
ListNode *pre; ListNode *pre;

View File

@ -44,7 +44,7 @@ string strRepeat(string str, int n) {
return os.str(); return os.str();
} }
/* Print an Array */ /* 打印数组 */
template <typename T> void printArray(T *arr, int n) { template <typename T> void printArray(T *arr, int n) {
cout << "["; cout << "[";
for (int i = 0; i < n - 1; i++) { for (int i = 0; i < n - 1; i++) {
@ -61,12 +61,12 @@ template <typename T> string getVectorString(vector<T> &list) {
return "[" + strJoin(", ", list) + "]"; return "[" + strJoin(", ", list) + "]";
} }
/* Print a vector */ /* 打印列表 */
template <typename T> void printVector(vector<T> list) { template <typename T> void printVector(vector<T> list) {
cout << getVectorString(list) << '\n'; cout << getVectorString(list) << '\n';
} }
/* Print a vector matrix */ /* 打印矩阵 */
template <typename T> void printVectorMatrix(vector<vector<T>> &matrix) { template <typename T> void printVectorMatrix(vector<vector<T>> &matrix) {
cout << "[" << '\n'; cout << "[" << '\n';
for (vector<T> &list : matrix) for (vector<T> &list : matrix)
@ -74,7 +74,7 @@ template <typename T> void printVectorMatrix(vector<vector<T>> &matrix) {
cout << "]" << '\n'; cout << "]" << '\n';
} }
/* Print a linked list */ /* 打印链表 */
void printLinkedList(ListNode *head) { void printLinkedList(ListNode *head) {
vector<int> list; vector<int> list;
while (head != nullptr) { while (head != nullptr) {
@ -85,10 +85,6 @@ void printLinkedList(ListNode *head) {
cout << strJoin(" -> ", list) << '\n'; cout << strJoin(" -> ", list) << '\n';
} }
/**
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
struct Trunk { struct Trunk {
Trunk *prev; Trunk *prev;
string str; string str;
@ -98,7 +94,6 @@ struct Trunk {
} }
}; };
/* Helper function to print branches of the binary tree */
void showTrunks(Trunk *p) { void showTrunks(Trunk *p) {
if (p == nullptr) { if (p == nullptr) {
return; return;
@ -108,7 +103,11 @@ void showTrunks(Trunk *p) {
cout << p->str; cout << p->str;
} }
/* Print a binary tree */ /**
*
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
void printTree(TreeNode *root, Trunk *prev, bool isRight) { void printTree(TreeNode *root, Trunk *prev, bool isRight) {
if (root == nullptr) { if (root == nullptr) {
return; return;
@ -140,12 +139,12 @@ void printTree(TreeNode *root, Trunk *prev, bool isRight) {
printTree(root->left, &trunk, false); printTree(root->left, &trunk, false);
} }
/* The interface of the tree printer */ /* 打印二叉树 */
void printTree(TreeNode *root) { void printTree(TreeNode *root) {
printTree(root, nullptr, false); printTree(root, nullptr, false);
} }
/* Print a stack */ /* 打印栈 */
template <typename T> void printStack(stack<T> stk) { template <typename T> void printStack(stack<T> stk) {
// Reverse the input stack // Reverse the input stack
stack<T> tmp; stack<T> tmp;
@ -167,7 +166,7 @@ template <typename T> void printStack(stack<T> stk) {
cout << "[" + s.str() + "]" << '\n'; cout << "[" + s.str() + "]" << '\n';
} }
/* Print a queue */ /* 打印队列 */
template <typename T> void printQueue(queue<T> queue) { template <typename T> void printQueue(queue<T> queue) {
// Generate the string to print // Generate the string to print
ostringstream s; ostringstream s;
@ -183,7 +182,7 @@ template <typename T> void printQueue(queue<T> queue) {
cout << "[" + s.str() + "]" << '\n'; cout << "[" + s.str() + "]" << '\n';
} }
/* Print a deque */ /* 打印双向队列 */
template <typename T> void printDeque(deque<T> deque) { template <typename T> void printDeque(deque<T> deque) {
// Generate the string to print // Generate the string to print
ostringstream s; ostringstream s;
@ -199,7 +198,7 @@ template <typename T> void printDeque(deque<T> deque) {
cout << "[" + s.str() + "]" << '\n'; cout << "[" + s.str() + "]" << '\n';
} }
/* Print a HashMap */ /* 打印哈希表 */
// 定义模板参数 TKey 和 TValue ,用于指定键值对的类型 // 定义模板参数 TKey 和 TValue ,用于指定键值对的类型
template <typename TKey, typename TValue> void printHashMap(unordered_map<TKey, TValue> map) { template <typename TKey, typename TValue> void printHashMap(unordered_map<TKey, TValue> map) {
for (auto kv : map) { for (auto kv : map) {
@ -217,7 +216,7 @@ template <typename T, typename S, typename C> S &Container(priority_queue<T, S,
return HackedQueue::Container(pq); return HackedQueue::Container(pq);
} }
/* Print a Heap (PriorityQueue) */ /* 打印堆(优先队列) */
template <typename T, typename S, typename C> void printHeap(priority_queue<T, S, C> &heap) { template <typename T, typename S, typename C> void printHeap(priority_queue<T, S, C> &heap) {
vector<T> vec = Container(heap); vector<T> vec = Container(heap);
cout << "堆的数组表示:"; cout << "堆的数组表示:";

View File

@ -4,12 +4,12 @@
namespace hello_algo.utils; namespace hello_algo.utils;
/* Definition for a singly-linked list node */ /* 链表节点 */
public class ListNode(int x) { public class ListNode(int x) {
public int val = x; public int val = x;
public ListNode? next; public ListNode? next;
/* Generate a linked list with an array */ /* 将数组反序列化为链表 */
public static ListNode? ArrToLinkedList(int[] arr) { public static ListNode? ArrToLinkedList(int[] arr) {
ListNode dum = new(0); ListNode dum = new(0);
ListNode head = dum; ListNode head = dum;
@ -20,14 +20,6 @@ public class ListNode(int x) {
return dum.next; return dum.next;
} }
/* Get a list node with specific value from a linked list */
public static ListNode? GetListNode(ListNode? head, int val) {
while (head != null && head.val != val) {
head = head.next;
}
return head;
}
public override string? ToString() { public override string? ToString() {
List<string> list = []; List<string> list = [];
var head = this; var head = this;

View File

@ -12,7 +12,7 @@ public class Trunk(Trunk? prev, string str) {
}; };
public static class PrintUtil { public static class PrintUtil {
/* Print a list */ /* 打印列表 */
public static void PrintList<T>(IList<T> list) { public static void PrintList<T>(IList<T> list) {
Console.WriteLine("[" + string.Join(", ", list) + "]"); Console.WriteLine("[" + string.Join(", ", list) + "]");
} }
@ -21,7 +21,7 @@ public static class PrintUtil {
return $"[ {string.Join(", ", list.Select(x => x?.ToString() ?? "null"))} ]"; return $"[ {string.Join(", ", list.Select(x => x?.ToString() ?? "null"))} ]";
} }
/* Print a matrix (Array) */ /* 打印矩阵 (Array) */
public static void PrintMatrix<T>(T[][] matrix) { public static void PrintMatrix<T>(T[][] matrix) {
Console.WriteLine("["); Console.WriteLine("[");
foreach (T[] row in matrix) { foreach (T[] row in matrix) {
@ -30,7 +30,7 @@ public static class PrintUtil {
Console.WriteLine("]"); Console.WriteLine("]");
} }
/* Print a matrix (List) */ /* 打印矩阵 (List) */
public static void PrintMatrix<T>(List<List<T>> matrix) { public static void PrintMatrix<T>(List<List<T>> matrix) {
Console.WriteLine("["); Console.WriteLine("[");
foreach (List<T> row in matrix) { foreach (List<T> row in matrix) {
@ -39,7 +39,7 @@ public static class PrintUtil {
Console.WriteLine("]"); Console.WriteLine("]");
} }
/* Print a linked list */ /* 打印链表 */
public static void PrintLinkedList(ListNode? head) { public static void PrintLinkedList(ListNode? head) {
List<string> list = []; List<string> list = [];
while (head != null) { while (head != null) {
@ -50,7 +50,7 @@ public static class PrintUtil {
} }
/** /**
* The interface of the tree printer *
* This tree printer is borrowed from TECHIE DELIGHT * This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/ * https://www.techiedelight.com/c-program-print-binary-tree/
*/ */
@ -58,7 +58,7 @@ public static class PrintUtil {
PrintTree(root, null, false); PrintTree(root, null, false);
} }
/* Print a binary tree */ /* 打印二叉树 */
public static void PrintTree(TreeNode? root, Trunk? prev, bool isRight) { public static void PrintTree(TreeNode? root, Trunk? prev, bool isRight) {
if (root == null) { if (root == null) {
return; return;
@ -90,7 +90,6 @@ public static class PrintUtil {
PrintTree(root.left, trunk, false); PrintTree(root.left, trunk, false);
} }
/* Helper function to print branches of the binary tree */
public static void ShowTrunks(Trunk? p) { public static void ShowTrunks(Trunk? p) {
if (p == null) { if (p == null) {
return; return;
@ -100,14 +99,14 @@ public static class PrintUtil {
Console.Write(p.str); Console.Write(p.str);
} }
/* Print a hash map */ /* 打印哈希表 */
public static void PrintHashMap<K, V>(Dictionary<K, V> map) where K : notnull { public static void PrintHashMap<K, V>(Dictionary<K, V> map) where K : notnull {
foreach (var kv in map.Keys) { foreach (var kv in map.Keys) {
Console.WriteLine(kv.ToString() + " -> " + map[kv]?.ToString()); Console.WriteLine(kv.ToString() + " -> " + map[kv]?.ToString());
} }
} }
/* Print a heap */ /* 打印堆 */
public static void PrintHeap(Queue<int> queue) { public static void PrintHeap(Queue<int> queue) {
Console.Write("堆的数组表示:"); Console.Write("堆的数组表示:");
List<int> list = [.. queue]; List<int> list = [.. queue];
@ -117,7 +116,7 @@ public static class PrintUtil {
PrintTree(tree); PrintTree(tree);
} }
/* Print a PriorityQueue */ /* 打印优先队列 */
public static void PrintHeap(PriorityQueue<int, int> queue) { public static void PrintHeap(PriorityQueue<int, int> queue) {
var newQueue = new PriorityQueue<int, int>(queue.UnorderedItems, queue.Comparer); var newQueue = new PriorityQueue<int, int>(queue.UnorderedItems, queue.Comparer);
Console.Write("堆的数组表示:"); Console.Write("堆的数组表示:");

View File

@ -4,7 +4,7 @@
* Author: Jefferson (JeffersonHuang77@gmail.com) * Author: Jefferson (JeffersonHuang77@gmail.com)
*/ */
/* Definition for a singly-linked list node */ /* 链表节点 */
class ListNode { class ListNode {
int val; int val;
ListNode? next; ListNode? next;
@ -12,7 +12,7 @@ class ListNode {
ListNode(this.val, [this.next]); ListNode(this.val, [this.next]);
} }
/* Generate a linked list with a list */ /* 将列表反序列化为链表 */
ListNode? listToLinkedList(List<int> list) { ListNode? listToLinkedList(List<int> list) {
ListNode dum = ListNode(0); ListNode dum = ListNode(0);
ListNode? head = dum; ListNode? head = dum;

View File

@ -16,7 +16,7 @@ class Trunk {
Trunk(this.prev, this.str); Trunk(this.prev, this.str);
} }
/* Print a matrix (Array) */ /* 打印矩阵 (Array) */
void printMatrix(List<List<int>> matrix) { void printMatrix(List<List<int>> matrix) {
print("["); print("[");
for (List<int> row in matrix) { for (List<int> row in matrix) {
@ -25,7 +25,7 @@ void printMatrix(List<List<int>> matrix) {
print("]"); print("]");
} }
/* Print a linked list */ /* 打印链表 */
void printLinkedList(ListNode? head) { void printLinkedList(ListNode? head) {
List<String> list = []; List<String> list = [];
@ -38,7 +38,7 @@ void printLinkedList(ListNode? head) {
} }
/** /**
* The interface of the tree printer *
* This tree printer is borrowed from TECHIE DELIGHT * This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/ * https://www.techiedelight.com/c-program-print-binary-tree/
*/ */
@ -72,7 +72,6 @@ void printTree(TreeNode? root, [Trunk? prev = null, bool isRight = false]) {
printTree(root.left, trunk, false); printTree(root.left, trunk, false);
} }
/* Helper function to print branches of the binary tree */
void showTrunks(Trunk? p) { void showTrunks(Trunk? p) {
if (p == null) { if (p == null) {
return; return;
@ -82,7 +81,7 @@ void showTrunks(Trunk? p) {
stdout.write(p.str); stdout.write(p.str);
} }
/* Print a heap (PriorityQueue) */ /* 打印堆 */
void printHeap(List<int> heap) { void printHeap(List<int> heap) {
print("堆的数组表示:$heap"); print("堆的数组表示:$heap");
print("堆的树状表示:"); print("堆的树状表示:");

View File

@ -64,7 +64,7 @@ func (q *arrayDeque) pushLast(num int) {
} }
// 计算队尾指针,指向队尾索引 + 1 // 计算队尾指针,指向队尾索引 + 1
rear := q.index(q.front + q.queSize) rear := q.index(q.front + q.queSize)
// 将 num 添加至队 // 将 num 添加至队
q.nums[rear] = num q.nums[rear] = num
q.queSize++ q.queSize++
} }

View File

@ -4,13 +4,13 @@
package pkg package pkg
// ListNode Definition for a singly-linked list node // ListNode 链表节点
type ListNode struct { type ListNode struct {
Next *ListNode Next *ListNode
Val int Val int
} }
// NewListNode Generate a list node with an val // NewListNode 链表节点构造函数
func NewListNode(v int) *ListNode { func NewListNode(v int) *ListNode {
return &ListNode{ return &ListNode{
Next: nil, Next: nil,
@ -18,7 +18,7 @@ func NewListNode(v int) *ListNode {
} }
} }
// ArrayToLinkedList Generate a linked list with an array // ArrayToLinkedList 将数组反序列化为链表
func ArrayToLinkedList(arr []int) *ListNode { func ArrayToLinkedList(arr []int) *ListNode {
// dummy header of linked list // dummy header of linked list
dummy := NewListNode(0) dummy := NewListNode(0)
@ -29,11 +29,3 @@ func ArrayToLinkedList(arr []int) *ListNode {
} }
return dummy.Next return dummy.Next
} }
// GetListNode Get a list node with specific value from a linked list
func GetListNode(node *ListNode, val int) *ListNode {
for node != nil && node.Val != val {
node = node.Next
}
return node
}

View File

@ -5,7 +5,6 @@
package pkg package pkg
import ( import (
"fmt"
"testing" "testing"
) )
@ -14,6 +13,4 @@ func TestListNode(t *testing.T) {
head := ArrayToLinkedList(arr) head := ArrayToLinkedList(arr)
PrintLinkedList(head) PrintLinkedList(head)
node := GetListNode(head, 5)
fmt.Println("Find node: ", node.Val)
} }

View File

@ -11,13 +11,13 @@ import (
"strings" "strings"
) )
// PrintSlice Print a slice // PrintSlice 打印切片
func PrintSlice[T any](nums []T) { func PrintSlice[T any](nums []T) {
fmt.Printf("%v", nums) fmt.Printf("%v", nums)
fmt.Println() fmt.Println()
} }
// PrintList Print a list // PrintList 打印列表
func PrintList(list *list.List) { func PrintList(list *list.List) {
if list.Len() == 0 { if list.Len() == 0 {
fmt.Print("[]\n") fmt.Print("[]\n")
@ -33,14 +33,14 @@ func PrintList(list *list.List) {
fmt.Print(e.Value, "]\n") fmt.Print(e.Value, "]\n")
} }
// PrintMap Print a hash map // PrintMap 打印哈希表
func PrintMap[K comparable, V any](m map[K]V) { func PrintMap[K comparable, V any](m map[K]V) {
for key, value := range m { for key, value := range m {
fmt.Println(key, "->", value) fmt.Println(key, "->", value)
} }
} }
// PrintHeap Print a heap // PrintHeap 打印堆
func PrintHeap(h []any) { func PrintHeap(h []any) {
fmt.Printf("堆的数组表示:") fmt.Printf("堆的数组表示:")
fmt.Printf("%v", h) fmt.Printf("%v", h)
@ -49,7 +49,7 @@ func PrintHeap(h []any) {
PrintTree(root) PrintTree(root)
} }
// PrintLinkedList Print a linked list // PrintLinkedList 打印链表
func PrintLinkedList(node *ListNode) { func PrintLinkedList(node *ListNode) {
if node == nil { if node == nil {
return return
@ -63,12 +63,12 @@ func PrintLinkedList(node *ListNode) {
fmt.Println(builder.String()) fmt.Println(builder.String())
} }
// PrintTree Print a binary tree // PrintTree 打印二叉树
func PrintTree(root *TreeNode) { func PrintTree(root *TreeNode) {
printTreeHelper(root, nil, false) printTreeHelper(root, nil, false)
} }
// printTreeHelper Help to print a binary tree, hide more details // printTreeHelper 打印二叉树
// This tree printer is borrowed from TECHIE DELIGHT // This tree printer is borrowed from TECHIE DELIGHT
// https://www.techiedelight.com/c-program-print-binary-tree/ // https://www.techiedelight.com/c-program-print-binary-tree/
func printTreeHelper(root *TreeNode, prev *trunk, isRight bool) { func printTreeHelper(root *TreeNode, prev *trunk, isRight bool) {
@ -96,7 +96,6 @@ func printTreeHelper(root *TreeNode, prev *trunk, isRight bool) {
printTreeHelper(root.Left, trunk, false) printTreeHelper(root.Left, trunk, false)
} }
// trunk Help to print tree structure
type trunk struct { type trunk struct {
prev *trunk prev *trunk
str string str string

View File

@ -4,6 +4,7 @@
package pkg package pkg
// TreeNode 二叉树节点
type TreeNode struct { type TreeNode struct {
Val any // 节点值 Val any // 节点值
Height int // 节点高度 Height int // 节点高度
@ -11,6 +12,7 @@ type TreeNode struct {
Right *TreeNode // 右子节点引用 Right *TreeNode // 右子节点引用
} }
// NewTreeNode 二叉树节点构造函数
func NewTreeNode(v any) *TreeNode { func NewTreeNode(v any) *TreeNode {
return &TreeNode{ return &TreeNode{
Val: v, Val: v,

View File

@ -9,14 +9,14 @@ type Vertex struct {
Val int Val int
} }
// NewVertex 构造函数 // NewVertex 顶点构造函数
func NewVertex(val int) Vertex { func NewVertex(val int) Vertex {
return Vertex{ return Vertex{
Val: val, Val: val,
} }
} }
// ValsToVets Generate a vertex list tree given an array // ValsToVets 将值列表反序列化为顶点列表
func ValsToVets(vals []int) []Vertex { func ValsToVets(vals []int) []Vertex {
vets := make([]Vertex, len(vals)) vets := make([]Vertex, len(vals))
for i := 0; i < len(vals); i++ { for i := 0; i < len(vals); i++ {
@ -25,7 +25,7 @@ func ValsToVets(vals []int) []Vertex {
return vets return vets
} }
// VetsToVals Serialize given vertex list to a value list // VetsToVals 将顶点列表序列化为值列表
func VetsToVals(vets []Vertex) []int { func VetsToVals(vets []Vertex) []int {
vals := make([]int, len(vets)) vals := make([]int, len(vets))
for i := range vets { for i := range vets {

View File

@ -6,7 +6,7 @@
package utils; package utils;
/* Definition for a singly-linked list node */ /* 链表节点 */
public class ListNode { public class ListNode {
public int val; public int val;
public ListNode next; public ListNode next;
@ -15,7 +15,7 @@ public class ListNode {
val = x; val = x;
} }
/* Generate a linked list with an array */ /* 将列表反序列化为链表 */
public static ListNode arrToLinkedList(int[] arr) { public static ListNode arrToLinkedList(int[] arr) {
ListNode dum = new ListNode(0); ListNode dum = new ListNode(0);
ListNode head = dum; ListNode head = dum;
@ -25,12 +25,4 @@ public class ListNode {
} }
return dum.next; return dum.next;
} }
/* Get a list node with specific value from a linked list */
public static ListNode getListNode(ListNode head, int val) {
while (head != null && head.val != val) {
head = head.next;
}
return head;
}
} }

View File

@ -19,8 +19,7 @@ class Trunk {
}; };
public class PrintUtil { public class PrintUtil {
/* 打印矩阵Array */
/* Print a matrix (Array) */
public static <T> void printMatrix(T[][] matrix) { public static <T> void printMatrix(T[][] matrix) {
System.out.println("["); System.out.println("[");
for (T[] row : matrix) { for (T[] row : matrix) {
@ -29,7 +28,7 @@ public class PrintUtil {
System.out.println("]"); System.out.println("]");
} }
/* Print a matrix (List) */ /* 打印矩阵List */
public static <T> void printMatrix(List<List<T>> matrix) { public static <T> void printMatrix(List<List<T>> matrix) {
System.out.println("["); System.out.println("[");
for (List<T> row : matrix) { for (List<T> row : matrix) {
@ -38,7 +37,7 @@ public class PrintUtil {
System.out.println("]"); System.out.println("]");
} }
/* Print a linked list */ /* 打印链表 */
public static void printLinkedList(ListNode head) { public static void printLinkedList(ListNode head) {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
while (head != null) { while (head != null) {
@ -48,16 +47,16 @@ public class PrintUtil {
System.out.println(String.join(" -> ", list)); System.out.println(String.join(" -> ", list));
} }
/** /* 打印二叉树 */
* The interface of the tree printer
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
public static void printTree(TreeNode root) { public static void printTree(TreeNode root) {
printTree(root, null, false); printTree(root, null, false);
} }
/* Print a binary tree */ /**
* 打印二叉树
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
public static void printTree(TreeNode root, Trunk prev, boolean isRight) { public static void printTree(TreeNode root, Trunk prev, boolean isRight) {
if (root == null) { if (root == null) {
return; return;
@ -89,7 +88,6 @@ public class PrintUtil {
printTree(root.left, trunk, false); printTree(root.left, trunk, false);
} }
/* Helper function to print branches of the binary tree */
public static void showTrunks(Trunk p) { public static void showTrunks(Trunk p) {
if (p == null) { if (p == null) {
return; return;
@ -99,14 +97,14 @@ public class PrintUtil {
System.out.print(p.str); System.out.print(p.str);
} }
/* Print a hash map */ /* 打印哈希表 */
public static <K, V> void printHashMap(Map<K, V> map) { public static <K, V> void printHashMap(Map<K, V> map) {
for (Map.Entry<K, V> kv : map.entrySet()) { for (Map.Entry<K, V> kv : map.entrySet()) {
System.out.println(kv.getKey() + " -> " + kv.getValue()); System.out.println(kv.getKey() + " -> " + kv.getValue());
} }
} }
/* Print a heap (PriorityQueue) */ /* 打印堆(优先队列) */
public static void printHeap(Queue<Integer> queue) { public static void printHeap(Queue<Integer> queue) {
List<Integer> list = new ArrayList<>(queue); List<Integer> list = new ArrayList<>(queue);
System.out.print("堆的数组表示:"); System.out.print("堆的数组表示:");

View File

@ -4,9 +4,7 @@
* Author: IsChristina (christinaxia77@foxmail.com) * Author: IsChristina (christinaxia77@foxmail.com)
*/ */
/** /* 链表节点 */
* Definition for a singly-linked list node
*/
class ListNode { class ListNode {
val; // 节点值 val; // 节点值
next; // 指向下一节点的引用(指针) next; // 指向下一节点的引用(指针)
@ -16,11 +14,7 @@ class ListNode {
} }
} }
/** /* 将列表反序列化为链表 */
* Generate a linked list with an array
* @param arr
* @return
*/
function arrToLinkedList(arr) { function arrToLinkedList(arr) {
const dum = new ListNode(0); const dum = new ListNode(0);
let head = dum; let head = dum;
@ -31,21 +25,7 @@ function arrToLinkedList(arr) {
return dum.next; return dum.next;
} }
/**
* Get a list node with specific value from a linked list
* @param head
* @param val
* @return
*/
function getListNode(head, val) {
while (head !== null && head.val !== val) {
head = head.next;
}
return head;
}
module.exports = { module.exports = {
ListNode, ListNode,
arrToLinkedList, arrToLinkedList,
getListNode,
}; };

View File

@ -6,10 +6,7 @@
const { arrToTree } = require('./TreeNode'); const { arrToTree } = require('./TreeNode');
/** /* 打印链表 */
* Print a linked list
* @param head
*/
function printLinkedList(head) { function printLinkedList(head) {
let list = []; let list = [];
while (head !== null) { while (head !== null) {
@ -25,21 +22,15 @@ function Trunk(prev, str) {
} }
/** /**
* The interface of the tree printer * 打印二叉树
* This tree printer is borrowed from TECHIE DELIGHT * This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/ * https://www.techiedelight.com/c-program-print-binary-tree/
* @param root
*/ */
function printTree(root) { function printTree(root) {
printTree(root, null, false); printTree(root, null, false);
} }
/** /* 打印二叉树 */
* Print a binary tree
* @param root
* @param prev
* @param isRight
*/
function printTree(root, prev, isRight) { function printTree(root, prev, isRight) {
if (root === null) { if (root === null) {
return; return;
@ -71,10 +62,6 @@ function printTree(root, prev, isRight) {
printTree(root.left, trunk, false); printTree(root.left, trunk, false);
} }
/**
* Helper function to print branches of the binary tree
* @param p
*/
function showTrunks(p) { function showTrunks(p) {
if (!p) { if (!p) {
return; return;
@ -84,10 +71,7 @@ function showTrunks(p) {
process.stdout.write(p.str); process.stdout.write(p.str);
} }
/** /* 打印堆 */
* Print a heap
* @param arr
*/
function printHeap(arr) { function printHeap(arr) {
console.log('堆的数组表示:'); console.log('堆的数组表示:');
console.log(arr); console.log(arr);

View File

@ -4,9 +4,7 @@
* Author: IsChristina (christinaxia77@foxmail.com) * Author: IsChristina (christinaxia77@foxmail.com)
*/ */
/** /* 二叉树节点 */
* Definition for a binary tree node.
*/
class TreeNode { class TreeNode {
val; // 节点值 val; // 节点值
left; // 左子节点指针 left; // 左子节点指针
@ -20,11 +18,7 @@ class TreeNode {
} }
} }
/** /* 将数组反序列化为二叉树 */
* Generate a binary tree given an array
* @param arr
* @return
*/
function arrToTree(arr, i = 0) { function arrToTree(arr, i = 0) {
if (i < 0 || i >= arr.length || arr[i] === null) { if (i < 0 || i >= arr.length || arr[i] === null) {
return null; return null;

View File

@ -11,7 +11,7 @@ class ListNode(var value: Int) {
var next: ListNode? = null var next: ListNode? = null
companion object { companion object {
/* 将列表序列化为链表 */ /* 将列表序列化为链表 */
fun arrToLinkedList(arr: IntArray): ListNode? { fun arrToLinkedList(arr: IntArray): ListNode? {
val dum = ListNode(0) val dum = ListNode(0)
var head = dum var head = dum
@ -21,14 +21,5 @@ class ListNode(var value: Int) {
} }
return dum.next return dum.next
} }
/* 获取链表中值为 value 的节点 */
fun getListNode(h: ListNode, value: Int): ListNode {
var head = h
while (head.value != value) {
head = head.next!!
}
return head
}
} }
} }

View File

@ -14,7 +14,7 @@ class ListNode:
def list_to_linked_list(arr: list[int]) -> ListNode | None: def list_to_linked_list(arr: list[int]) -> ListNode | None:
"""将列表序列化为链表""" """将列表序列化为链表"""
dum = head = ListNode(0) dum = head = ListNode(0)
for a in arr: for a in arr:
node = ListNode(a) node = ListNode(a)
@ -24,7 +24,7 @@ def list_to_linked_list(arr: list[int]) -> ListNode | None:
def linked_list_to_list(head: ListNode | None) -> list[int]: def linked_list_to_list(head: ListNode | None) -> list[int]:
"""将链表序列化为列表""" """将链表序列化为列表"""
arr: list[int] = [] arr: list[int] = []
while head: while head:
arr.append(head.val) arr.append(head.val)

View File

@ -15,7 +15,7 @@ class ListNode
end end
end end
### 将列表序列化为链表 ### ### 将列表序列化为链表 ###
def arr_to_linked_list(arr) def arr_to_linked_list(arr)
head = current = ListNode.new arr[0] head = current = ListNode.new arr[0]
@ -27,7 +27,7 @@ def arr_to_linked_list(arr)
head head
end end
### 将链表序列化为列表 ### ### 将链表序列化为列表 ###
def linked_list_to_arr(head) def linked_list_to_arr(head)
arr = [] arr = []

View File

@ -19,7 +19,7 @@ impl<T> ListNode<T> {
Rc::new(RefCell::new(ListNode { val, next: None })) Rc::new(RefCell::new(ListNode { val, next: None }))
} }
/* Generate a linked list with an array */ /* 将数组反序列化为链表 */
pub fn arr_to_linked_list(array: &[T]) -> Option<Rc<RefCell<ListNode<T>>>> pub fn arr_to_linked_list(array: &[T]) -> Option<Rc<RefCell<ListNode<T>>>>
where where
T: Copy + Clone, T: Copy + Clone,
@ -36,7 +36,7 @@ impl<T> ListNode<T> {
head head
} }
/* Generate a hashmap with a linked_list */ /* 将链表转化为哈希表 */
pub fn linked_list_to_hashmap( pub fn linked_list_to_hashmap(
linked_list: Option<Rc<RefCell<ListNode<T>>>>, linked_list: Option<Rc<RefCell<ListNode<T>>>>,
) -> HashMap<T, Rc<RefCell<ListNode<T>>>> ) -> HashMap<T, Rc<RefCell<ListNode<T>>>>

View File

@ -17,7 +17,7 @@ struct Trunk<'a, 'b> {
str: Cell<&'b str>, str: Cell<&'b str>,
} }
/* Print an array */ /* 打印数组 */
pub fn print_array<T: Display>(nums: &[T]) { pub fn print_array<T: Display>(nums: &[T]) {
print!("["); print!("[");
if nums.len() > 0 { if nums.len() > 0 {
@ -29,14 +29,14 @@ pub fn print_array<T: Display>(nums: &[T]) {
} }
} }
/* Print a hash map */ /* 打印哈希表 */
pub fn print_hash_map<TKey: Display, TValue: Display>(map: &HashMap<TKey, TValue>) { pub fn print_hash_map<TKey: Display, TValue: Display>(map: &HashMap<TKey, TValue>) {
for (key, value) in map { for (key, value) in map {
println!("{key} -> {value}"); println!("{key} -> {value}");
} }
} }
/* Print a queue or deque */ /* 打印队列(双向队列) */
pub fn print_queue<T: Display>(queue: &VecDeque<T>) { pub fn print_queue<T: Display>(queue: &VecDeque<T>) {
print!("["); print!("[");
let iter = queue.iter(); let iter = queue.iter();
@ -45,7 +45,7 @@ pub fn print_queue<T: Display>(queue: &VecDeque<T>) {
} }
} }
/* Print a linked list */ /* 打印链表 */
pub fn print_linked_list<T: Display>(head: &Rc<RefCell<ListNode<T>>>) { pub fn print_linked_list<T: Display>(head: &Rc<RefCell<ListNode<T>>>) {
print!("{}{}", head.borrow().val, if head.borrow().next.is_none() {"\n"} else {" -> "}); print!("{}{}", head.borrow().val, if head.borrow().next.is_none() {"\n"} else {" -> "});
if let Some(node) = &head.borrow().next { if let Some(node) = &head.borrow().next {
@ -53,10 +53,12 @@ pub fn print_linked_list<T: Display>(head: &Rc<RefCell<ListNode<T>>>) {
} }
} }
/* 打印二叉树 */
pub fn print_tree(root: &Rc<RefCell<TreeNode>>) { pub fn print_tree(root: &Rc<RefCell<TreeNode>>) {
_print_tree(Some(root), None, false); _print_tree(Some(root), None, false);
} }
/* 打印二叉树 */
fn _print_tree(root: Option<&Rc<RefCell<TreeNode>>>, prev: Option<&Trunk>, is_right: bool) { fn _print_tree(root: Option<&Rc<RefCell<TreeNode>>>, prev: Option<&Trunk>, is_right: bool) {
if let Some(node) = root { if let Some(node) = root {
let mut prev_str = " "; let mut prev_str = " ";
@ -91,7 +93,7 @@ fn show_trunks(trunk: Option<&Trunk>) {
} }
} }
/* Print a heap both in array and tree representations */ /* 打印堆 */
pub fn print_heap(heap: Vec<i32>) { pub fn print_heap(heap: Vec<i32>) {
println!("堆的数组表示:{:?}", heap); println!("堆的数组表示:{:?}", heap);
println!("堆的树状表示:"); println!("堆的树状表示:");

View File

@ -4,9 +4,7 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
/** /* 链表节点 */
* Definition for a singly-linked list node
*/
class ListNode { class ListNode {
val: number; val: number;
next: ListNode | null; next: ListNode | null;
@ -16,11 +14,7 @@ class ListNode {
} }
} }
/** /* 将数组反序列化为链表 */
* Generate a linked list with an array
* @param arr
* @return
*/
function arrToLinkedList(arr: number[]): ListNode | null { function arrToLinkedList(arr: number[]): ListNode | null {
const dum: ListNode = new ListNode(0); const dum: ListNode = new ListNode(0);
let head = dum; let head = dum;
@ -31,17 +25,4 @@ function arrToLinkedList(arr: number[]): ListNode | null {
return dum.next; return dum.next;
} }
/** export { ListNode, arrToLinkedList };
* Get a list node with specific value from a linked list
* @param head
* @param val
* @return
*/
function getListNode(head: ListNode | null, val: number): ListNode | null {
while (head !== null && head.val !== val) {
head = head.next;
}
return head;
}
export { ListNode, arrToLinkedList, getListNode };

View File

@ -7,10 +7,7 @@
import { ListNode } from './ListNode'; import { ListNode } from './ListNode';
import { TreeNode, arrToTree } from './TreeNode'; import { TreeNode, arrToTree } from './TreeNode';
/** /* 打印链表 */
* Print a linked list
* @param head
*/
function printLinkedList(head: ListNode | null): void { function printLinkedList(head: ListNode | null): void {
const list: string[] = []; const list: string[] = [];
while (head !== null) { while (head !== null) {
@ -31,21 +28,15 @@ class Trunk {
} }
/** /**
* The interface of the tree printer *
* This tree printer is borrowed from TECHIE DELIGHT * This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/ * https://www.techiedelight.com/c-program-print-binary-tree/
* @param root
*/ */
function printTree(root: TreeNode | null) { function printTree(root: TreeNode | null) {
printTreeHelper(root, null, false); printTreeHelper(root, null, false);
} }
/** /* 打印二叉树 */
* Print a binary tree
* @param root
* @param prev
* @param isRight
*/
function printTreeHelper( function printTreeHelper(
root: TreeNode | null, root: TreeNode | null,
prev: Trunk | null, prev: Trunk | null,
@ -81,10 +72,6 @@ function printTreeHelper(
printTreeHelper(root.left, trunk, false); printTreeHelper(root.left, trunk, false);
} }
/**
* Helper function to print branches of the binary tree
* @param p
*/
function showTrunks(p: Trunk | null) { function showTrunks(p: Trunk | null) {
if (p === null) { if (p === null) {
return; return;
@ -97,10 +84,7 @@ function showTrunks(p: Trunk | null) {
// restart the vscode // restart the vscode
} }
/** /* 打印堆 */
* Print a heap
* @param arr
*/
function printHeap(arr: number[]): void { function printHeap(arr: number[]): void {
console.log('堆的数组表示:'); console.log('堆的数组表示:');
console.log(arr); console.log(arr);

View File

@ -4,9 +4,7 @@
* Author: Justin (xiefahit@gmail.com) * Author: Justin (xiefahit@gmail.com)
*/ */
/** /* 二叉树节点 */
* Definition for a binary tree node.
*/
class TreeNode { class TreeNode {
val: number; // 节点值 val: number; // 节点值
height: number; // 节点高度 height: number; // 节点高度
@ -25,11 +23,7 @@ class TreeNode {
} }
} }
/** /* 将数组反序列化为二叉树 */
* Generate a binary tree given an array
* @param arr
* @return
*/
function arrToTree(arr: (number | null)[], i: number = 0): TreeNode | null { function arrToTree(arr: (number | null)[], i: number = 0): TreeNode | null {
if (i < 0 || i >= arr.length || arr[i] === null) { if (i < 0 || i >= arr.length || arr[i] === null) {
return null; return null;

View File

@ -4,7 +4,7 @@
const std = @import("std"); const std = @import("std");
// Definition for a singly-linked list node //
pub fn ListNode(comptime T: type) type { pub fn ListNode(comptime T: type) type {
return struct { return struct {
const Self = @This(); const Self = @This();
@ -20,7 +20,7 @@ pub fn ListNode(comptime T: type) type {
}; };
} }
// Generate a linked list with a list //
pub fn listToLinkedList(comptime T: type, mem_allocator: std.mem.Allocator, list: std.ArrayList(T)) !?*ListNode(T) { 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)); var dum = try mem_allocator.create(ListNode(T));
dum.init(0); dum.init(0);
@ -34,7 +34,7 @@ pub fn listToLinkedList(comptime T: type, mem_allocator: std.mem.Allocator, list
return dum.next; return dum.next;
} }
// Generate a linked list with an array //
pub fn arrToLinkedList(comptime T: type, mem_allocator: std.mem.Allocator, arr: []T) !?*ListNode(T) { pub fn arrToLinkedList(comptime T: type, mem_allocator: std.mem.Allocator, arr: []T) !?*ListNode(T) {
var dum = try mem_allocator.create(ListNode(T)); var dum = try mem_allocator.create(ListNode(T));
dum.init(0); dum.init(0);

View File

@ -8,7 +8,7 @@ pub const ListNode = ListUtil.ListNode;
pub const TreeUtil = @import("TreeNode.zig"); pub const TreeUtil = @import("TreeNode.zig");
pub const TreeNode = TreeUtil.TreeNode; pub const TreeNode = TreeUtil.TreeNode;
// Print an array //
pub fn printArray(comptime T: type, nums: []T) void { pub fn printArray(comptime T: type, nums: []T) void {
std.debug.print("[", .{}); std.debug.print("[", .{});
if (nums.len > 0) { if (nums.len > 0) {
@ -20,7 +20,7 @@ pub fn printArray(comptime T: type, nums: []T) void {
} }
} }
// Print a list //
pub fn printList(comptime T: type, list: std.ArrayList(T)) void { pub fn printList(comptime T: type, list: std.ArrayList(T)) void {
std.debug.print("[", .{}); std.debug.print("[", .{});
if (list.items.len > 0) { if (list.items.len > 0) {
@ -32,7 +32,7 @@ pub fn printList(comptime T: type, list: std.ArrayList(T)) void {
} }
} }
// Print a linked list //
pub fn printLinkedList(comptime T: type, node: ?*ListNode(T)) !void { pub fn printLinkedList(comptime T: type, node: ?*ListNode(T)) !void {
if (node == null) return; if (node == null) return;
var list = std.ArrayList(T).init(std.heap.page_allocator); var list = std.ArrayList(T).init(std.heap.page_allocator);
@ -47,7 +47,7 @@ pub fn printLinkedList(comptime T: type, node: ?*ListNode(T)) !void {
} }
} }
// Print a queue or deque //
pub fn printQueue(comptime T: type, queue: std.TailQueue(T)) void { pub fn printQueue(comptime T: type, queue: std.TailQueue(T)) void {
var node = queue.first; var node = queue.first;
std.debug.print("[", .{}); std.debug.print("[", .{});
@ -59,7 +59,7 @@ pub fn printQueue(comptime T: type, queue: std.TailQueue(T)) void {
} }
} }
// Print a hash map //
pub fn printHashMap(comptime TKey: type, comptime TValue: type, map: std.AutoHashMap(TKey, TValue)) void { pub fn printHashMap(comptime TKey: type, comptime TValue: type, map: std.AutoHashMap(TKey, TValue)) void {
var it = map.iterator(); var it = map.iterator();
while (it.next()) |kv| { while (it.next()) |kv| {
@ -69,7 +69,7 @@ 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 { pub fn printHeap(comptime T: type, mem_allocator: std.mem.Allocator, queue: anytype) !void {
var arr = queue.items; var arr = queue.items;
var len = queue.len; var len = queue.len;
@ -80,6 +80,7 @@ pub fn printHeap(comptime T: type, mem_allocator: std.mem.Allocator, queue: anyt
try printTree(root, null, false); try printTree(root, null, false);
} }
//
// This tree printer is borrowed from TECHIE DELIGHT // This tree printer is borrowed from TECHIE DELIGHT
// https://www.techiedelight.com/c-program-print-binary-tree/ // https://www.techiedelight.com/c-program-print-binary-tree/
const Trunk = struct { const Trunk = struct {
@ -92,15 +93,13 @@ const Trunk = struct {
} }
}; };
// Helper function to print branches of the binary tree
pub fn showTrunks(p: ?*Trunk) void { pub fn showTrunks(p: ?*Trunk) void {
if (p == null) return; if (p == null) return;
showTrunks(p.?.prev); showTrunks(p.?.prev);
std.debug.print("{s}", .{p.?.str}); std.debug.print("{s}", .{p.?.str});
} }
// The interface of the tree printer //
// Print a binary tree
pub fn printTree(root: ?*TreeNode(i32), prev: ?*Trunk, isRight: bool) !void { pub fn printTree(root: ?*TreeNode(i32), prev: ?*Trunk, isRight: bool) !void {
if (root == null) { if (root == null) {
return; return;

View File

@ -4,7 +4,7 @@
const std = @import("std"); const std = @import("std");
// Definition for a binary tree node //
pub fn TreeNode(comptime T: type) type { pub fn TreeNode(comptime T: type) type {
return struct { return struct {
const Self = @This(); const Self = @This();
@ -24,7 +24,7 @@ pub fn TreeNode(comptime T: type) type {
}; };
} }
// Generate a binary tree with an array //
pub fn arrToTree(comptime T: type, mem_allocator: std.mem.Allocator, arr: []T) !?*TreeNode(T) { pub fn arrToTree(comptime T: type, mem_allocator: std.mem.Allocator, arr: []T) !?*TreeNode(T) {
if (arr.len == 0) return null; if (arr.len == 0) return null;
var root = try mem_allocator.create(TreeNode(T)); var root = try mem_allocator.create(TreeNode(T));

View File

@ -106,7 +106,7 @@
| adjacency list | 邻接表 | 鄰接表 | | adjacency list | 邻接表 | 鄰接表 |
| breadth-first search | 广度优先搜索 | 廣度優先搜尋 | | breadth-first search | 广度优先搜索 | 廣度優先搜尋 |
| depth-first search | 深度优先搜索 | 深度優先搜尋 | | depth-first search | 深度优先搜索 | 深度優先搜尋 |
| binary search | 二分查找 | 二分查找 | | binary search | 二分查找 | 二分搜尋 |
| searching algorithm | 搜索算法 | 搜尋演算法 | | searching algorithm | 搜索算法 | 搜尋演算法 |
| sorting algorithm | 排序算法 | 排序演算法 | | sorting algorithm | 排序算法 | 排序演算法 |
| selection sort | 选择排序 | 選擇排序 | | selection sort | 选择排序 | 選擇排序 |
@ -130,7 +130,7 @@
| $n$-queens problem | $n$ 皇后问题 | $n$ 皇后問題 | | $n$-queens problem | $n$ 皇后问题 | $n$ 皇后問題 |
| dynamic programming | 动态规划 | 動態規劃 | | dynamic programming | 动态规划 | 動態規劃 |
| initial state | 初始状态 | 初始狀態 | | initial state | 初始状态 | 初始狀態 |
| state-transition equation | 状态转移方程 | 狀態轉移方程 | | state-transition equation | 状态转移方程 | 狀態轉移方程 |
| knapsack problem | 背包问题 | 背包問題 | | knapsack problem | 背包问题 | 背包問題 |
| edit distance problem | 编辑距离问题 | 編輯距離問題 | | edit distance problem | 编辑距离问题 | 編輯距離問題 |
| greedy algorithm | 贪心算法 | 貪婪演算法 | | greedy algorithm | 贪心算法 | 貪婪演算法 |

View File

@ -700,7 +700,7 @@
} }
} }
/* 递归 O(n) */ /* 递归 O(n) */
void recur(n: i32) { fn recur(n: i32) {
if n == 1 { if n == 1 {
return; return;
} }

View File

@ -283,7 +283,7 @@
int size = deque.length; int size = deque.length;
/* 判断双向队列是否为空 */ /* 判断双向队列是否为空 */
bool isEmpty = deque.isEmpty;W bool isEmpty = deque.isEmpty;
``` ```
=== "Rust" === "Rust"