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"
#define ARRAY_SIZE 10
#define SIZE 10
/* 比较两个浮点数的大小 */
int compare_float(const void *a, const void *b) {
@ -28,8 +28,8 @@ void bucketSort(float nums[], int size) {
int k = size / 2;
float **buckets = calloc(k, sizeof(float *));
for (int i = 0; i < k; i++) {
// 每个桶最多可以分配 k 个元素
buckets[i] = calloc(ARRAY_SIZE, sizeof(float));
// 每个桶最多可以分配 size 个元素
buckets[i] = calloc(size, sizeof(float));
}
// 1. 将数组元素分配到各个桶中
@ -42,7 +42,7 @@ void bucketSort(float nums[], int size) {
j++;
}
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]);
j++;
}
@ -51,12 +51,12 @@ void bucketSort(float nums[], int size) {
// 2. 对各个桶执行排序
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. 遍历桶合并结果
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) {
nums[i++] = buckets[j][l];
}
@ -73,10 +73,10 @@ void bucketSort(float nums[], int size) {
/* Driver Code */
int main() {
// 设输入数据为浮点数,范围为 [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};
bucketSort(nums, ARRAY_SIZE);
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, SIZE);
printf("桶排序完成后 nums = ");
printArrayFloat(nums, ARRAY_SIZE);
printArrayFloat(nums, SIZE);
return 0;
}

View File

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

View File

@ -26,7 +26,7 @@ ListNode *newListNode(int val) {
return node;
}
/* Generate a linked list with an array */
/* 将数组反序列化为链表 */
ListNode *arrToLinkedList(const int *arr, size_t size) {
if (size <= 0) {
return NULL;
@ -41,15 +41,7 @@ ListNode *arrToLinkedList(const int *arr, size_t size) {
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) {
// 释放内存
ListNode *pre;

View File

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

View File

@ -11,7 +11,7 @@
using namespace std;
/* Definition for a singly-linked list node */
/* 链表节点 */
struct ListNode {
int val;
ListNode *next;
@ -19,7 +19,7 @@ struct ListNode {
}
};
/* Generate a linked list with a vector */
/* 将列表反序列化为链表 */
ListNode *vecToLinkedList(vector<int> list) {
ListNode *dum = new ListNode(0);
ListNode *head = dum;
@ -30,15 +30,7 @@ ListNode *vecToLinkedList(vector<int> list) {
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) {
// 释放内存
ListNode *pre;

View File

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

View File

@ -4,12 +4,12 @@
namespace hello_algo.utils;
/* Definition for a singly-linked list node */
/* 链表节点 */
public class ListNode(int x) {
public int val = x;
public ListNode? next;
/* Generate a linked list with an array */
/* 将数组反序列化为链表 */
public static ListNode? ArrToLinkedList(int[] arr) {
ListNode dum = new(0);
ListNode head = dum;
@ -20,14 +20,6 @@ public class ListNode(int x) {
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() {
List<string> list = [];
var head = this;

View File

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

View File

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

View File

@ -16,7 +16,7 @@ class Trunk {
Trunk(this.prev, this.str);
}
/* Print a matrix (Array) */
/* 打印矩阵 (Array) */
void printMatrix(List<List<int>> matrix) {
print("[");
for (List<int> row in matrix) {
@ -25,7 +25,7 @@ void printMatrix(List<List<int>> matrix) {
print("]");
}
/* Print a linked list */
/* 打印链表 */
void printLinkedList(ListNode? head) {
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
* 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);
}
/* Helper function to print branches of the binary tree */
void showTrunks(Trunk? p) {
if (p == null) {
return;
@ -82,7 +81,7 @@ void showTrunks(Trunk? p) {
stdout.write(p.str);
}
/* Print a heap (PriorityQueue) */
/* 打印堆 */
void printHeap(List<int> heap) {
print("堆的数组表示:$heap");
print("堆的树状表示:");

View File

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

View File

@ -4,13 +4,13 @@
package pkg
// ListNode Definition for a singly-linked list node
// ListNode 链表节点
type ListNode struct {
Next *ListNode
Val int
}
// NewListNode Generate a list node with an val
// NewListNode 链表节点构造函数
func NewListNode(v int) *ListNode {
return &ListNode{
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 {
// dummy header of linked list
dummy := NewListNode(0)
@ -29,11 +29,3 @@ func ArrayToLinkedList(arr []int) *ListNode {
}
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
import (
"fmt"
"testing"
)
@ -14,6 +13,4 @@ func TestListNode(t *testing.T) {
head := ArrayToLinkedList(arr)
PrintLinkedList(head)
node := GetListNode(head, 5)
fmt.Println("Find node: ", node.Val)
}

View File

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

View File

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

View File

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

View File

@ -6,7 +6,7 @@
package utils;
/* Definition for a singly-linked list node */
/* 链表节点 */
public class ListNode {
public int val;
public ListNode next;
@ -15,7 +15,7 @@ public class ListNode {
val = x;
}
/* Generate a linked list with an array */
/* 将列表反序列化为链表 */
public static ListNode arrToLinkedList(int[] arr) {
ListNode dum = new ListNode(0);
ListNode head = dum;
@ -25,12 +25,4 @@ public class ListNode {
}
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 {
/* Print a matrix (Array) */
/* 打印矩阵Array */
public static <T> void printMatrix(T[][] matrix) {
System.out.println("[");
for (T[] row : matrix) {
@ -29,7 +28,7 @@ public class PrintUtil {
System.out.println("]");
}
/* Print a matrix (List) */
/* 打印矩阵List */
public static <T> void printMatrix(List<List<T>> matrix) {
System.out.println("[");
for (List<T> row : matrix) {
@ -38,7 +37,7 @@ public class PrintUtil {
System.out.println("]");
}
/* Print a linked list */
/* 打印链表 */
public static void printLinkedList(ListNode head) {
List<String> list = new ArrayList<>();
while (head != null) {
@ -48,16 +47,16 @@ public class PrintUtil {
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) {
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) {
if (root == null) {
return;
@ -89,7 +88,6 @@ public class PrintUtil {
printTree(root.left, trunk, false);
}
/* Helper function to print branches of the binary tree */
public static void showTrunks(Trunk p) {
if (p == null) {
return;
@ -99,14 +97,14 @@ public class PrintUtil {
System.out.print(p.str);
}
/* Print a hash map */
/* 打印哈希表 */
public static <K, V> void printHashMap(Map<K, V> map) {
for (Map.Entry<K, V> kv : map.entrySet()) {
System.out.println(kv.getKey() + " -> " + kv.getValue());
}
}
/* Print a heap (PriorityQueue) */
/* 打印堆(优先队列) */
public static void printHeap(Queue<Integer> queue) {
List<Integer> list = new ArrayList<>(queue);
System.out.print("堆的数组表示:");

View File

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

View File

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

View File

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

View File

@ -11,7 +11,7 @@ class ListNode(var value: Int) {
var next: ListNode? = null
companion object {
/* 将列表序列化为链表 */
/* 将列表序列化为链表 */
fun arrToLinkedList(arr: IntArray): ListNode? {
val dum = ListNode(0)
var head = dum
@ -21,14 +21,5 @@ class ListNode(var value: Int) {
}
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:
"""将列表序列化为链表"""
"""将列表序列化为链表"""
dum = head = ListNode(0)
for a in arr:
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]:
"""将链表序列化为列表"""
"""将链表序列化为列表"""
arr: list[int] = []
while head:
arr.append(head.val)

View File

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

View File

@ -19,7 +19,7 @@ impl<T> ListNode<T> {
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>>>>
where
T: Copy + Clone,
@ -36,7 +36,7 @@ impl<T> ListNode<T> {
head
}
/* Generate a hashmap with a linked_list */
/* 将链表转化为哈希表 */
pub fn linked_list_to_hashmap(
linked_list: Option<Rc<RefCell<ListNode<T>>>>,
) -> HashMap<T, Rc<RefCell<ListNode<T>>>>

View File

@ -17,7 +17,7 @@ struct Trunk<'a, 'b> {
str: Cell<&'b str>,
}
/* Print an array */
/* 打印数组 */
pub fn print_array<T: Display>(nums: &[T]) {
print!("[");
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>) {
for (key, value) in map {
println!("{key} -> {value}");
}
}
/* Print a queue or deque */
/* 打印队列(双向队列) */
pub fn print_queue<T: Display>(queue: &VecDeque<T>) {
print!("[");
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>>>) {
print!("{}{}", head.borrow().val, if head.borrow().next.is_none() {"\n"} else {" -> "});
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>>) {
_print_tree(Some(root), None, false);
}
/* 打印二叉树 */
fn _print_tree(root: Option<&Rc<RefCell<TreeNode>>>, prev: Option<&Trunk>, is_right: bool) {
if let Some(node) = root {
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>) {
println!("堆的数组表示:{:?}", heap);
println!("堆的树状表示:");

View File

@ -4,9 +4,7 @@
* Author: Justin (xiefahit@gmail.com)
*/
/**
* Definition for a singly-linked list node
*/
/* 链表节点 */
class ListNode {
val: number;
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 {
const dum: ListNode = new ListNode(0);
let head = dum;
@ -31,17 +25,4 @@ function arrToLinkedList(arr: number[]): ListNode | null {
return dum.next;
}
/**
* 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 };
export { ListNode, arrToLinkedList };

View File

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

View File

@ -4,9 +4,7 @@
* Author: Justin (xiefahit@gmail.com)
*/
/**
* Definition for a binary tree node.
*/
/* 二叉树节点 */
class TreeNode {
val: 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 {
if (i < 0 || i >= arr.length || arr[i] === null) {
return null;

View File

@ -4,7 +4,7 @@
const std = @import("std");
// Definition for a singly-linked list node
//
pub fn ListNode(comptime T: type) type {
return struct {
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) {
var dum = try mem_allocator.create(ListNode(T));
dum.init(0);
@ -34,7 +34,7 @@ pub fn listToLinkedList(comptime T: type, mem_allocator: std.mem.Allocator, list
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) {
var dum = try mem_allocator.create(ListNode(T));
dum.init(0);

View File

@ -8,7 +8,7 @@ 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 {
std.debug.print("[", .{});
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 {
std.debug.print("[", .{});
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 {
if (node == null) return;
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 {
var node = queue.first;
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 {
var it = map.iterator();
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 {
var arr = queue.items;
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);
}
//
// This tree printer is borrowed from TECHIE DELIGHT
// https://www.techiedelight.com/c-program-print-binary-tree/
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 {
if (p == null) return;
showTrunks(p.?.prev);
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 {
if (root == null) {
return;

View File

@ -4,7 +4,7 @@
const std = @import("std");
// Definition for a binary tree node
//
pub fn TreeNode(comptime T: type) type {
return struct {
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) {
if (arr.len == 0) return null;
var root = try mem_allocator.create(TreeNode(T));

View File

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

View File

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

View File

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