diff --git a/codes/c/chapter_array_and_linkedlist/array.c b/codes/c/chapter_array_and_linkedlist/array.c index 9ffb29c26..621ee6582 100644 --- a/codes/c/chapter_array_and_linkedlist/array.c +++ b/codes/c/chapter_array_and_linkedlist/array.c @@ -1,117 +1,117 @@ -/** - * File: array.c - * Created Time: 2022-12-20 - * Author: MolDuM (moldum@163.com) - */ - -#include "../utils/common.h" - -/* 随机访问元素 */ -int randomAccess(int *nums, int size) { - // 在区间 [0, size) 中随机抽取一个数字 - int randomIndex = rand() % size; - // 获取并返回随机元素 - int randomNum = nums[randomIndex]; - return randomNum; -} - -/* 扩展数组长度 */ -int *extend(int *nums, int size, int enlarge) { - // 初始化一个扩展长度后的数组 - int *res = (int *)malloc(sizeof(int) * (size + enlarge)); - // 将原数组中的所有元素复制到新数组 - for (int i = 0; i < size; i++) { - res[i] = nums[i]; - } - // 初始化扩展后的空间 - for (int i = size; i < size + enlarge; i++) { - res[i] = 0; - } - // 返回扩展后的新数组 - return res; -} - -/* 在数组的索引 index 处插入元素 num */ -void insert(int *nums, int size, int num, int index) { - // 把索引 index 以及之后的所有元素向后移动一位 - for (int i = size - 1; i > index; i--) { - nums[i] = nums[i - 1]; - } - // 将 num 赋给 index 处的元素 - nums[index] = num; -} - -/* 删除索引 index 处的元素 */ -// 注意:stdio.h 占用了 remove 关键词 -void removeItem(int *nums, int size, int index) { - // 把索引 index 之后的所有元素向前移动一位 - for (int i = index; i < size - 1; i++) { - nums[i] = nums[i + 1]; - } -} - -/* 遍历数组 */ -void traverse(int *nums, int size) { - int count = 0; - // 通过索引遍历数组 - for (int i = 0; i < size; i++) { - count += nums[i]; - } -} - -/* 在数组中查找指定元素 */ -int find(int *nums, int size, int target) { - for (int i = 0; i < size; i++) { - if (nums[i] == target) - return i; - } - return -1; -} - -/* Driver Code */ -int main() { - /* 初始化随机种子(只需执行一次) */ - srand((unsigned)time(NULL)); - - /* 初始化数组 */ - int size = 5; - int arr[5]; - printf("数组 arr = "); - printArray(arr, size); - - int nums[] = {1, 3, 2, 5, 4}; - printf("数组 nums = "); - printArray(nums, size); - - /* 随机访问 */ - int randomNum = randomAccess(nums, size); - printf("在 nums 中获取随机元素 %d", randomNum); - - /* 长度扩展 */ - int enlarge = 3; - int *res = extend(nums, size, enlarge); - size += enlarge; - printf("将数组长度扩展至 8 ,得到 nums = "); - printArray(res, size); - - /* 插入元素 */ - insert(res, size, 6, 3); - printf("在索引 3 处插入数字 6 ,得到 nums = "); - printArray(res, size); - - /* 删除元素 */ - removeItem(res, size, 2); - printf("删除索引 2 处的元素,得到 nums = "); - printArray(res, size); - - /* 遍历数组 */ - traverse(res, size); - - /* 查找元素 */ - int index = find(res, size, 3); - printf("在 res 中查找元素 3 ,得到索引 = %d\n", index); - - /* 释放内存 */ - free(res); - return 0; -} +/** + * File: array.c + * Created Time: 2022-12-20 + * Author: MolDuM (moldum@163.com) + */ + +#include "../utils/common.h" + +/* 随机访问元素 */ +int randomAccess(int *nums, int size) { + // 在区间 [0, size) 中随机抽取一个数字 + int randomIndex = rand() % size; + // 获取并返回随机元素 + int randomNum = nums[randomIndex]; + return randomNum; +} + +/* 扩展数组长度 */ +int *extend(int *nums, int size, int enlarge) { + // 初始化一个扩展长度后的数组 + int *res = (int *)malloc(sizeof(int) * (size + enlarge)); + // 将原数组中的所有元素复制到新数组 + for (int i = 0; i < size; i++) { + res[i] = nums[i]; + } + // 初始化扩展后的空间 + for (int i = size; i < size + enlarge; i++) { + res[i] = 0; + } + // 返回扩展后的新数组 + return res; +} + +/* 在数组的索引 index 处插入元素 num */ +void insert(int *nums, int size, int num, int index) { + // 把索引 index 以及之后的所有元素向后移动一位 + for (int i = size - 1; i > index; i--) { + nums[i] = nums[i - 1]; + } + // 将 num 赋给 index 处的元素 + nums[index] = num; +} + +/* 删除索引 index 处的元素 */ +// 注意:stdio.h 占用了 remove 关键词 +void removeItem(int *nums, int size, int index) { + // 把索引 index 之后的所有元素向前移动一位 + for (int i = index; i < size - 1; i++) { + nums[i] = nums[i + 1]; + } +} + +/* 遍历数组 */ +void traverse(int *nums, int size) { + int count = 0; + // 通过索引遍历数组 + for (int i = 0; i < size; i++) { + count += nums[i]; + } +} + +/* 在数组中查找指定元素 */ +int find(int *nums, int size, int target) { + for (int i = 0; i < size; i++) { + if (nums[i] == target) + return i; + } + return -1; +} + +/* Driver Code */ +int main() { + /* 初始化随机种子(只需执行一次) */ + srand((unsigned)time(NULL)); + + /* 初始化数组 */ + int size = 5; + int arr[5] = {0}; + printf("数组 arr = "); + printArray(arr, size); + + int nums[] = {1, 3, 2, 5, 4}; + printf("数组 nums = "); + printArray(nums, size); + + /* 随机访问 */ + int randomNum = randomAccess(nums, size); + printf("在 nums 中获取随机元素 %d", randomNum); + + /* 长度扩展 */ + int enlarge = 3; + int *res = extend(nums, size, enlarge); + size += enlarge; + printf("将数组长度扩展至 8 ,得到 nums = "); + printArray(res, size); + + /* 插入元素 */ + insert(res, size, 6, 3); + printf("在索引 3 处插入数字 6 ,得到 nums = "); + printArray(res, size); + + /* 删除元素 */ + removeItem(res, size, 2); + printf("删除索引 2 处的元素,得到 nums = "); + printArray(res, size); + + /* 遍历数组 */ + traverse(res, size); + + /* 查找元素 */ + int index = find(res, size, 3); + printf("在 res 中查找元素 3 ,得到索引 = %d\n", index); + + /* 释放内存 */ + free(res); + return 0; +} diff --git a/codes/c/chapter_stack_and_queue/linkedlist_deque.c b/codes/c/chapter_stack_and_queue/linkedlist_deque.c index 367554cc7..27e74bb45 100644 --- a/codes/c/chapter_stack_and_queue/linkedlist_deque.c +++ b/codes/c/chapter_stack_and_queue/linkedlist_deque.c @@ -182,7 +182,7 @@ int main() { int peekFirstNum = peekFirst(deque); printf("队首元素 peekFirst = %d\r\n", peekFirstNum); int peekLastNum = peekLast(deque); - printf("队首元素 peekLast = %d\r\n", peekLastNum); + printf("队尾元素 peekLast = %d\r\n", peekLastNum); /* 元素入队 */ pushLast(deque, 4); diff --git a/codes/c/utils/list_node.h b/codes/c/utils/list_node.h index 78db68784..1907fe833 100644 --- a/codes/c/utils/list_node.h +++ b/codes/c/utils/list_node.h @@ -14,7 +14,7 @@ extern "C" { /* 链表节点结构体 */ typedef struct ListNode { int val; // 节点值 - struct ListNode *next; // 指向下一节点的引用 + struct ListNode *next; // 指向下一节点的指针 } ListNode; /* 构造函数,初始化一个新节点 */ diff --git a/codes/cpp/chapter_array_and_linkedlist/array.cpp b/codes/cpp/chapter_array_and_linkedlist/array.cpp index dd87b9240..769b78e02 100644 --- a/codes/cpp/chapter_array_and_linkedlist/array.cpp +++ b/codes/cpp/chapter_array_and_linkedlist/array.cpp @@ -18,7 +18,7 @@ int randomAccess(int *nums, int size) { /* 扩展数组长度 */ int *extend(int *nums, int size, int enlarge) { // 初始化一个扩展长度后的数组 - int *res = new int[size + enlarge]; + int *res = new int[size + enlarge]{}; // 将原数组中的所有元素复制到新数组 for (int i = 0; i < size; i++) { res[i] = nums[i]; @@ -69,7 +69,7 @@ int find(int *nums, int size, int target) { int main() { /* 初始化数组 */ int size = 5; - int *arr = new int[size]; + int *arr = new int[size]{}; cout << "数组 arr = "; printArray(arr, size); diff --git a/codes/dart/chapter_hashing/hash_map.dart b/codes/dart/chapter_hashing/hash_map.dart index 811d3dac2..d5893d3c9 100644 --- a/codes/dart/chapter_hashing/hash_map.dart +++ b/codes/dart/chapter_hashing/hash_map.dart @@ -36,6 +36,5 @@ void main() { print("\n单独遍历键 Key"); map.keys.forEach((key) => print(key)); print("\n单独遍历值 Value"); - map.forEach((key, value) => print("$value")); map.values.forEach((value) => print(value)); } diff --git a/codes/dart/chapter_tree/binary_tree.dart b/codes/dart/chapter_tree/binary_tree.dart index 757578b41..31ba438af 100644 --- a/codes/dart/chapter_tree/binary_tree.dart +++ b/codes/dart/chapter_tree/binary_tree.dart @@ -9,7 +9,7 @@ import '../utils/tree_node.dart'; void main() { /* 初始化二叉树 */ - // 舒适化节点 + // 初始化节点 TreeNode n1 = TreeNode(1); TreeNode n2 = TreeNode(2); TreeNode n3 = TreeNode(3); diff --git a/codes/go/chapter_heap/heap_test.go b/codes/go/chapter_heap/heap_test.go index 4b84a05e5..90417d3d3 100644 --- a/codes/go/chapter_heap/heap_test.go +++ b/codes/go/chapter_heap/heap_test.go @@ -91,8 +91,6 @@ func TestMyHeap(t *testing.T) { } func TestTopKHeap(t *testing.T) { - /* 初始化堆 */ - // 初始化大顶堆 nums := []int{1, 7, 6, 3, 2} k := 3 res := topKHeap(nums, k) diff --git a/codes/go/chapter_stack_and_queue/deque_test.go b/codes/go/chapter_stack_and_queue/deque_test.go index f68a958d0..060e868ad 100644 --- a/codes/go/chapter_stack_and_queue/deque_test.go +++ b/codes/go/chapter_stack_and_queue/deque_test.go @@ -51,7 +51,6 @@ func TestDeque(t *testing.T) { func TestArrayDeque(t *testing.T) { /* 初始化双向队列 */ - // 在 Go 中,将 list 作为双向队列使用 deque := newArrayDeque(16) /* 元素入队 */ @@ -102,7 +101,7 @@ func TestLinkedListDeque(t *testing.T) { deque.pushLast(4) deque.pushFirst(3) deque.pushFirst(1) - fmt.Print("队列 deque = ") + fmt.Print("双向队列 deque = ") PrintList(deque.toList()) // 访问队首元素 diff --git a/codes/go/chapter_stack_and_queue/queue_test.go b/codes/go/chapter_stack_and_queue/queue_test.go index c25f0f12d..26da17868 100644 --- a/codes/go/chapter_stack_and_queue/queue_test.go +++ b/codes/go/chapter_stack_and_queue/queue_test.go @@ -84,7 +84,7 @@ func TestArrayQueue(t *testing.T) { for i := 0; i < 10; i++ { queue.push(i) queue.pop() - fmt.Print("第", i, "轮入队 + 出队后 queue =") + fmt.Print("第 ", i, " 轮入队 + 出队后 queue =") PrintSlice(queue.toSlice()) } } diff --git a/codes/java/chapter_array_and_linkedlist/list.java b/codes/java/chapter_array_and_linkedlist/list.java index 317807153..69804b7c8 100644 --- a/codes/java/chapter_array_and_linkedlist/list.java +++ b/codes/java/chapter_array_and_linkedlist/list.java @@ -11,7 +11,7 @@ import java.util.*; public class list { public static void main(String[] args) { /* 初始化列表 */ - // 注意数组的元素类型是 int[] 的包装类 Integer[] + // 注意数组类型需为 Integer[] 而非 int[],因为列表元素只能是 int 的包装类 Integer Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); System.out.println("列表 nums = " + nums); diff --git a/codes/python/chapter_hashing/built_in_hash.py b/codes/python/chapter_hashing/built_in_hash.py index 90c534c30..77ed495fe 100644 --- a/codes/python/chapter_hashing/built_in_hash.py +++ b/codes/python/chapter_hashing/built_in_hash.py @@ -30,7 +30,7 @@ if __name__ == "__main__": tup = (12836, "小哈") hash_tup = hash(tup) - print(f"元组 {tup} 的哈希值为 {hash(hash_tup)}") + print(f"元组 {tup} 的哈希值为 {hash_tup}") obj = ListNode(0) hash_obj = hash(obj) diff --git a/codes/ruby/chapter_hashing/built_in_hash.rb b/codes/ruby/chapter_hashing/built_in_hash.rb index 6136db50f..c40621a0a 100644 --- a/codes/ruby/chapter_hashing/built_in_hash.rb +++ b/codes/ruby/chapter_hashing/built_in_hash.rb @@ -24,9 +24,9 @@ if __FILE__ == $0 hash_str = str.hash puts "字符串 #{str} 的哈希值为 #{hash_str}" - tup = [12836, '小哈'] - hash_tup = tup.hash - puts "元组 #{tup} 的哈希值为 #{hash_tup}" + arr = [12836, '小哈'] + hash_arr = arr.hash + puts "数组 #{arr} 的哈希值为 #{hash_arr}" obj = ListNode.new(0) hash_obj = obj.hash diff --git a/codes/ruby/chapter_stack_and_queue/array_deque.rb b/codes/ruby/chapter_stack_and_queue/array_deque.rb index 91e4ff71f..474a61688 100644 --- a/codes/ruby/chapter_stack_and_queue/array_deque.rb +++ b/codes/ruby/chapter_stack_and_queue/array_deque.rb @@ -127,13 +127,13 @@ if __FILE__ == $0 deque.push_last(4) puts "元素 4 队尾入队后 deque = #{deque.to_array}" deque.push_first(1) - puts "元素 1 队尾入队后 deque = #{deque.to_array}" + puts "元素 1 队首入队后 deque = #{deque.to_array}" # 元素出队 pop_last = deque.pop_last puts "队尾出队元素 = #{pop_last},队尾出队后 deque = #{deque.to_array}" pop_first = deque.pop_first - puts "队尾出队元素 = #{pop_first},队尾出队后 deque = #{deque.to_array}" + puts "队首出队元素 = #{pop_first},队首出队后 deque = #{deque.to_array}" # 获取双向队列的长度 size = deque.size diff --git a/codes/ruby/chapter_stack_and_queue/deque.rb b/codes/ruby/chapter_stack_and_queue/deque.rb index 21e63d294..be102efc3 100644 --- a/codes/ruby/chapter_stack_and_queue/deque.rb +++ b/codes/ruby/chapter_stack_and_queue/deque.rb @@ -7,10 +7,10 @@ Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) ### Driver Code ### if __FILE__ == $0 # 初始化双向队列 - # Ruby 没有内直的双端队列,只能把 Array 当作双端队列来使用 + # Ruby 没有内置的双端队列,只能把 Array 当作双端队列来使用 deque = [] - # 元素如队 + # 元素入队 deque << 2 deque << 5 deque << 4 @@ -26,7 +26,7 @@ if __FILE__ == $0 puts "队尾元素 peek_last = #{peek_last}" # 元素出队 - # 请注意,由于是数组, Array#shift 方法的时间复杂度为 O(n) + # 请注意,由于是数组,Array#shift 方法的时间复杂度为 O(n) pop_front = deque.shift puts "队首出队元素 pop_front = #{pop_front},队首出队后 deque = #{deque}" pop_back = deque.pop diff --git a/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb b/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb index a138827eb..bd91e4a7b 100644 --- a/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,11 +4,11 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end -### 双向链表节点 +### 双向链表节点 ### class ListNode attr_accessor :val attr_accessor :next # 后继节点引用 - attr_accessor :prev # 前躯节点引用 + attr_accessor :prev # 前驱节点引用 ### 构造方法 ### def initialize(val) @@ -101,7 +101,7 @@ class LinkedListDeque pop(true) end - ### 队首出队 ### + ### 队尾出队 ### def pop_last pop(false) end @@ -145,7 +145,7 @@ if __FILE__ == $0 peek_first = deque.peek_first puts "队首元素 peek_first = #{peek_first}" peek_last = deque.peek_last - puts "队首元素 peek_last = #{peek_last}" + puts "队尾元素 peek_last = #{peek_last}" # 元素入队 deque.push_last(4) diff --git a/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb b/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb index fea3fc9cc..34bbd3971 100644 --- a/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb +++ b/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb @@ -74,7 +74,7 @@ if __FILE__ == $0 # 初始化队列 queue = LinkedListQueue.new - # 元素如队 + # 元素入队 queue.push(1) queue.push(3) queue.push(2) diff --git a/codes/ruby/chapter_stack_and_queue/queue.rb b/codes/ruby/chapter_stack_and_queue/queue.rb index 919289d37..0c1dcbbb8 100644 --- a/codes/ruby/chapter_stack_and_queue/queue.rb +++ b/codes/ruby/chapter_stack_and_queue/queue.rb @@ -7,7 +7,7 @@ Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) ### Driver Code ### if __FILE__ == $0 # 初始化队列 - # Ruby 内置的队列(Thread::Queue) 没有 peek 和遍历方法,可以把 Array 当作队列来使用 + # Ruby 内置的队列(Thread::Queue)没有 peek 和遍历方法,可以把 Array 当作队列来使用 queue = [] # 元素入队 @@ -23,7 +23,7 @@ if __FILE__ == $0 puts "队首元素 peek = #{peek}" # 元素出队 - # 清注意,由于是数组,Array#shift 方法时间复杂度为 O(n) + # 请注意,由于是数组,Array#shift 方法的时间复杂度为 O(n) pop = queue.shift puts "出队元素 pop = #{pop}" puts "出队后 queue = #{queue}" diff --git a/codes/rust/chapter_hashing/build_in_hash.rs b/codes/rust/chapter_hashing/build_in_hash.rs index 456f9791a..09a128f2d 100644 --- a/codes/rust/chapter_hashing/build_in_hash.rs +++ b/codes/rust/chapter_hashing/build_in_hash.rs @@ -45,5 +45,5 @@ fn main() { let mut hasher = DefaultHasher::new(); node.borrow().val.hash(&mut hasher); let hash = hasher.finish(); - println!("节点对象 {:?} 的哈希值为{}", node, hash); + println!("节点对象 {:?} 的哈希值为 {}", node, hash); } diff --git a/codes/rust/chapter_stack_and_queue/stack.rs b/codes/rust/chapter_stack_and_queue/stack.rs index b2df65b5b..ff81a50f4 100644 --- a/codes/rust/chapter_stack_and_queue/stack.rs +++ b/codes/rust/chapter_stack_and_queue/stack.rs @@ -9,7 +9,7 @@ use hello_algo_rust::include::print_util; /* Driver Code */ pub fn main() { // 初始化栈 - // 在 rust 中,推荐将 Vec 当作栈来使用 + // 在 Rust 中,推荐将 Vec 当作栈来使用 let mut stack: Vec = Vec::new(); // 元素入栈 diff --git a/codes/snippets/chapter_array_and_linkedlist/array.md b/codes/snippets/chapter_array_and_linkedlist/array.md index e28b909ba..e04be118c 100644 --- a/codes/snippets/chapter_array_and_linkedlist/array.md +++ b/codes/snippets/chapter_array_and_linkedlist/array.md @@ -9,10 +9,10 @@ nums: list[int] = [1, 3, 2, 5, 4] /* 初始化数组 */ // 存储在栈上 int arr[5] = {}; -int nums[5] = { 1, 3, 2, 5, 4 }; +int nums[5] = {1, 3, 2, 5, 4}; // 存储在堆上(需要手动释放空间) -int* arr1 = new int[5] {}; -int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +int *arr1 = new int[5]{}; +int *nums1 = new int[5]{1, 3, 2, 5, 4}; ``` ```java title="array.java" @@ -22,7 +22,7 @@ int[] nums = { 1, 3, 2, 5, 4 }; ``` ```csharp title="array.cs" -/* 初始化数组 */ +// 初始化数组 int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] int[] nums = [1, 3, 2, 5, 4]; ``` @@ -32,38 +32,37 @@ int[] nums = [1, 3, 2, 5, 4]; var arr [5]int // 在 Go 中,指定长度时([5]int)为数组,不指定长度时([]int)为切片 // 由于 Go 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度 -// 为了方便实现扩容 extend() 方法,以下将切片(Slice)看作数组(Array) +// 为了方便实现扩容 extend() 函数,以下将切片(Slice)看作数组(Array) nums := []int{1, 3, 2, 5, 4} ``` ```swift title="array.swift" /* 初始化数组 */ let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] -let nums = [1, 3, 2, 5, 4] +var nums = [1, 3, 2, 5, 4] ``` ```javascript title="array.js" /* 初始化数组 */ -var arr = new Array(5).fill(0); -var nums = [1, 3, 2, 5, 4]; +const arr = new Array(5).fill(0); +let nums = [1, 3, 2, 5, 4]; ``` ```typescript title="array.ts" /* 初始化数组 */ -let arr: number[] = new Array(5).fill(0); +const arr: number[] = new Array(5).fill(0); let nums: number[] = [1, 3, 2, 5, 4]; ``` ```dart title="array.dart" /* 初始化数组 */ -List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +var arr = List.filled(5, 0); // [0, 0, 0, 0, 0] List nums = [1, 3, 2, 5, 4]; ``` ```rust title="array.rs" /* 初始化数组 */ let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] -let slice: &[i32] = &[0; 5]; // 在 Rust 中,指定长度时([i32; 5])为数组,不指定长度时(&[i32])为切片 // 由于 Rust 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度 // Vector 是 Rust 一般情况下用作动态数组的类型 @@ -73,13 +72,13 @@ let nums: Vec = vec![1, 3, 2, 5, 4]; ```c title="array.c" /* 初始化数组 */ -int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } -int nums[5] = { 1, 3, 2, 5, 4 }; +int arr[5] = {0}; // { 0, 0, 0, 0, 0 } +int nums[] = {1, 3, 2, 5, 4}; ``` ```kotlin title="array.kt" /* 初始化数组 */ -var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +val arr = IntArray(5) // { 0, 0, 0, 0, 0 } var nums = intArrayOf(1, 3, 2, 5, 4) ``` diff --git a/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/codes/snippets/chapter_array_and_linkedlist/linked_list.md index b5163e888..abd73b8fb 100644 --- a/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -2,48 +2,53 @@ ```python title="" class ListNode: """链表节点类""" + def __init__(self, val: int): - self.val: int = val # 节点值 - self.next: ListNode | None = None # 指向下一节点的引用 + self.val: int = val # 节点值 + self.next: ListNode | None = None # 指向下一节点的引用 ``` ```cpp title="" -/* 链表节点结构体 */ +/* 链表节点 */ struct ListNode { - int val; // 节点值 - ListNode *next; // 指向下一节点的指针 - ListNode(int x) : val(x), next(nullptr) {} // 构造函数 + int val; // 节点值 + ListNode *next; // 后继节点指针 + ListNode(int x) : val(x), next(nullptr) { + } }; ``` ```java title="" -/* 链表节点类 */ -class ListNode { - int val; // 节点值 - ListNode next; // 指向下一节点的引用 - ListNode(int x) { val = x; } // 构造函数 +/* 链表节点 */ +public class ListNode { + public int val; // 节点值 + public ListNode next; // 指向下一节点的引用 + + public ListNode(int x) { + val = x; + } } ``` ```csharp title="" -/* 链表节点类 */ -class ListNode(int x) { //构造函数 - public int val = x; // 节点值 - public ListNode? next; // 指向下一节点的引用 +/* 链表节点 */ +public class ListNode(int x) { + public int val = x; // 节点值 + public ListNode? next; // 指向下一节点的引用 } ``` ```go title="" -/* 链表节点结构体 */ +// ListNode 链表节点 type ListNode struct { Val int // 节点值 - Next *ListNode // 指向下一节点的指针 + Next *ListNode // 后继节点指针 } -// NewListNode 构造函数,创建一个新的链表 -func NewListNode(val int) *ListNode { +// NewListNode 链表节点构造函数 +func NewListNode(v int) *ListNode { return &ListNode{ - Val: val, + Val: v, Next: nil, } } @@ -62,44 +67,54 @@ class ListNode { ``` ```javascript title="" -/* 链表节点类 */ +/* 链表节点 */ class ListNode { + val; // 节点值 + next; // 指向下一节点的引用(指针) constructor(val, next) { - this.val = (val === undefined ? 0 : val); // 节点值 - this.next = (next === undefined ? null : next); // 指向下一节点的引用 + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```typescript title="" -/* 链表节点类 */ +/* 链表节点 */ class ListNode { - val: number; - next: ListNode | null; + val: number; // 节点值 + next: ListNode | null; // 指向下一节点的引用 constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 节点值 - this.next = next === undefined ? null : next; // 指向下一节点的引用 + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```dart title="" -/* 链表节点类 */ +/* 链表节点 */ class ListNode { int val; // 节点值 ListNode? next; // 指向下一节点的引用 + ListNode(this.val, [this.next]); // 构造函数 } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; -/* 链表节点类 */ +use std::rc::Rc; + +/* 链表节点 */ #[derive(Debug)] -struct ListNode { - val: i32, // 节点值 - next: Option>>, // 指向下一节点的指针 +pub struct ListNode { + pub val: T, // 节点值 + pub next: Option>>>, // 后继节点指针 +} + +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None })) + } } ``` @@ -110,10 +125,10 @@ typedef struct ListNode { struct ListNode *next; // 指向下一节点的指针 } ListNode; -/* 构造函数 */ +/* 构造函数,初始化一个新节点 */ ListNode *newListNode(int val) { ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); + node = (ListNode *)malloc(sizeof(ListNode)); node->val = val; node->next = NULL; return node; @@ -121,16 +136,14 @@ ListNode *newListNode(int val) { ``` ```kotlin title="" -/* 链表节点类 */ -// 构造方法 -class ListNode(x: Int) { - val _val: Int = x // 节点值 - var next: ListNode? = null // 指向下一个节点的引用 +/* 链表节点 */ +class ListNode(var _val: Int) { + var next: ListNode? = null // 指向下一节点的引用 } ``` ```ruby title="" -# 链表节点类 +### 链表节点类 ### class ListNode attr_accessor :val # 节点值 attr_accessor :next # 指向下一节点的引用 @@ -161,11 +174,11 @@ n3.next = n4 ```cpp title="linked_list.cpp" /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ // 初始化各个节点 -ListNode* n0 = new ListNode(1); -ListNode* n1 = new ListNode(3); -ListNode* n2 = new ListNode(2); -ListNode* n3 = new ListNode(5); -ListNode* n4 = new ListNode(4); +ListNode *n0 = new ListNode(1); +ListNode *n1 = new ListNode(3); +ListNode *n2 = new ListNode(2); +ListNode *n3 = new ListNode(5); +ListNode *n4 = new ListNode(4); // 构建节点之间的引用 n0->next = n1; n1->next = n2; @@ -189,7 +202,7 @@ n3.next = n4; ``` ```csharp title="linked_list.cs" -/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化链表 1 -> 3 -> 2 -> 5 -> 4 // 初始化各个节点 ListNode n0 = new(1); ListNode n1 = new(3); @@ -211,6 +224,7 @@ n1 := NewListNode(3) n2 := NewListNode(2) n3 := NewListNode(5) n4 := NewListNode(4) + // 构建节点之间的引用 n0.Next = n1 n1.Next = n2 @@ -264,7 +278,7 @@ n3.next = n4; ``` ```dart title="linked_list.dart" -/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化链表 1 -> 3 -> 2 -> 5 -> 4 // 初始化各个节点 ListNode n0 = ListNode(1); ListNode n1 = ListNode(3); @@ -281,11 +295,11 @@ n3.next = n4; ```rust title="linked_list.rs" /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ // 初始化各个节点 -let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); -let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); -let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); -let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); -let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); +let n0 = ListNode::new(1); +let n1 = ListNode::new(3); +let n2 = ListNode::new(2); +let n3 = ListNode::new(5); +let n4 = ListNode::new(4); // 构建节点之间的引用 n0.borrow_mut().next = Some(n1.clone()); @@ -297,11 +311,11 @@ n3.borrow_mut().next = Some(n4.clone()); ```c title="linked_list.c" /* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */ // 初始化各个节点 -ListNode* n0 = newListNode(1); -ListNode* n1 = newListNode(3); -ListNode* n2 = newListNode(2); -ListNode* n3 = newListNode(5); -ListNode* n4 = newListNode(4); +ListNode *n0 = newListNode(1); +ListNode *n1 = newListNode(3); +ListNode *n2 = newListNode(2); +ListNode *n3 = newListNode(5); +ListNode *n4 = newListNode(4); // 构建节点之间的引用 n0->next = n1; n1->next = n2; @@ -317,11 +331,12 @@ val n1 = ListNode(3) val n2 = ListNode(2) val n3 = ListNode(5) val n4 = ListNode(4) + // 构建节点之间的引用 -n0.next = n1; -n1.next = n2; -n2.next = n3; -n3.next = n4; +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 ``` ```ruby title="linked_list.rb" @@ -345,39 +360,46 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2 ```python title="" class ListNode: - """双向链表节点类""" + """双向链表节点""" + def __init__(self, val: int): - self.val: int = val # 节点值 - self.next: ListNode | None = None # 指向后继节点的引用 - self.prev: ListNode | None = None # 指向前驱节点的引用 + """构造方法""" + self.val: int = val # 节点值 + self.next: ListNode | None = None # 后继节点引用 + self.prev: ListNode | None = None # 前驱节点引用 ``` ```cpp title="" -/* 双向链表节点结构体 */ -struct ListNode { - int val; // 节点值 - ListNode *next; // 指向后继节点的指针 - ListNode *prev; // 指向前驱节点的指针 - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 构造函数 +/* 双向链表节点 */ +struct DoublyListNode { + int val; // 节点值 + DoublyListNode *next; // 后继节点指针 + DoublyListNode *prev; // 前驱节点指针 + DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { + } }; ``` ```java title="" -/* 双向链表节点类 */ +/* 双向链表节点 */ class ListNode { - int val; // 节点值 - ListNode next; // 指向后继节点的引用 - ListNode prev; // 指向前驱节点的引用 - ListNode(int x) { val = x; } // 构造函数 + int val; // 节点值 + ListNode next; // 后继节点引用 + ListNode prev; // 前驱节点引用 + + ListNode(int val) { + this.val = val; + prev = next = null; + } } ``` ```csharp title="" -/* 双向链表节点类 */ -class ListNode(int x) { // 构造函数 - public int val = x; // 节点值 - public ListNode? next; // 指向后继节点的引用 - public ListNode? prev; // 指向前驱节点的引用 +/* 双向链表节点 */ +public class ListNode(int val) { + public int val = val; // 节点值 + public ListNode? next = null; // 后继节点引用 + public ListNode? prev = null; // 前驱节点引用 } ``` @@ -385,8 +407,8 @@ class ListNode(int x) { // 构造函数 /* 双向链表节点结构体 */ type DoublyListNode struct { Val int // 节点值 - Next *DoublyListNode // 指向后继节点的指针 - Prev *DoublyListNode // 指向前驱节点的指针 + Next *DoublyListNode // 后继节点指针 + Prev *DoublyListNode // 前驱节点指针 } // NewDoublyListNode 初始化 @@ -400,117 +422,119 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* 双向链表节点类 */ +/* 双向链表节点 */ class ListNode { var val: Int // 节点值 - var next: ListNode? // 指向后继节点的引用 - var prev: ListNode? // 指向前驱节点的引用 + var next: ListNode? // 后继节点引用 + weak var prev: ListNode? // 前驱节点引用 - init(x: Int) { // 构造函数 - val = x + init(val: Int) { + self.val = val } } ``` ```javascript title="" -/* 双向链表节点类 */ +/* 双向链表节点 */ class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // 节点值 - this.next = next === undefined ? null : next; // 指向后继节点的引用 - this.prev = prev === undefined ? null : prev; // 指向前驱节点的引用 + prev; // 前驱节点引用(指针) + next; // 后继节点引用(指针) + val; // 节点值 + + constructor(val) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```typescript title="" -/* 双向链表节点类 */ +/* 双向链表节点 */ class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 节点值 - this.next = next === undefined ? null : next; // 指向后继节点的引用 - this.prev = prev === undefined ? null : prev; // 指向前驱节点的引用 + prev: ListNode | null; // 前驱节点引用(指针) + next: ListNode | null; // 后继节点引用(指针) + val: number; // 节点值 + + constructor(val: number) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```dart title="" -/* 双向链表节点类 */ +/* 双向链表节点 */ class ListNode { - int val; // 节点值 - ListNode? next; // 指向后继节点的引用 - ListNode? prev; // 指向前驱节点的引用 - ListNode(this.val, [this.next, this.prev]); // 构造函数 + int val; // 节点值 + ListNode? next; // 后继节点引用 + ListNode? prev; // 前驱节点引用 + + ListNode(this.val, {this.next, this.prev}); } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; -/* 双向链表节点类型 */ -#[derive(Debug)] -struct ListNode { - val: i32, // 节点值 - next: Option>>, // 指向后继节点的指针 - prev: Option>>, // 指向前驱节点的指针 +/* 双向链表节点 */ +pub struct ListNode { + pub val: T, // 节点值 + pub next: Option>>>, // 后继节点指针 + pub prev: Option>>>, // 前驱节点指针 } -/* 构造函数 */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None, prev: None, - } + })) } } ``` ```c title="" -/* 双向链表节点结构体 */ -typedef struct ListNode { - int val; // 节点值 - struct ListNode *next; // 指向后继节点的指针 - struct ListNode *prev; // 指向前驱节点的指针 -} ListNode; +/* 双向链表节点 */ +typedef struct DoublyListNode { + int val; // 节点值 + struct DoublyListNode *next; // 后继节点指针 + struct DoublyListNode *prev; // 前驱节点指针 +} DoublyListNode; /* 构造函数 */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; +DoublyListNode *newDoublyListNode(int num) { + DoublyListNode *new = (DoublyListNode *)malloc(sizeof(DoublyListNode)); + new->val = num; + new->next = NULL; + new->prev = NULL; + return new; } ``` ```kotlin title="" -/* 双向链表节点类 */ -// 构造方法 -class ListNode(x: Int) { - val _val: Int = x // 节点值 - var next: ListNode? = null // 指向后继节点的引用 - var prev: ListNode? = null // 指向前驱节点的引用 +/* 双向链表节点 */ +class ListNode( + var _val: Int // 节点值 +) { + var next: ListNode? = null // 后继节点引用 + var prev: ListNode? = null // 前驱节点引用 } ``` ```ruby title="" -# 双向链表节点类 +### 双向链表节点 ### class ListNode - attr_accessor :val # 节点值 - attr_accessor :next # 指向后继节点的引用 - attr_accessor :prev # 指向前驱节点的引用 + attr_accessor :val # 节点值 + attr_accessor :next # 后继节点引用 + attr_accessor :prev # 前驱节点引用 - def initialize(val=0, next_node=nil, prev_node=nil) + ### 构造方法 ### + def initialize(val) @val = val - @next = next_node - @prev = prev_node end end ``` diff --git a/codes/snippets/chapter_array_and_linkedlist/list.md b/codes/snippets/chapter_array_and_linkedlist/list.md index e0903ad8e..b911afbb3 100644 --- a/codes/snippets/chapter_array_and_linkedlist/list.md +++ b/codes/snippets/chapter_array_and_linkedlist/list.md @@ -2,25 +2,24 @@ ```python title="list.py" # 初始化列表 # 无初始值 -nums1: list[int] = [] +empty_nums: list[int] = [] # 有初始值 nums: list[int] = [1, 3, 2, 5, 4] ``` ```cpp title="list.cpp" /* 初始化列表 */ -// 需注意,C++ 中 vector 即是本文描述的 nums // 无初始值 -vector nums1; +vector emptyNums; // 有初始值 -vector nums = { 1, 3, 2, 5, 4 }; +vector nums = {1, 3, 2, 5, 4}; ``` ```java title="list.java" /* 初始化列表 */ // 无初始值 -List nums1 = new ArrayList<>(); -// 有初始值(注意数组的元素类型需为 int[] 的包装类 Integer[]) +List emptyNums = new ArrayList<>(); +// 有初始值(注意数组类型需为 Integer[] 而非 int[],因为列表元素只能是 int 的包装类 Integer) Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); ``` @@ -28,7 +27,7 @@ List nums = new ArrayList<>(Arrays.asList(numbers)); ```csharp title="list.cs" /* 初始化列表 */ // 无初始值 -List nums1 = []; +List emptyNums = []; // 有初始值 int[] numbers = [1, 3, 2, 5, 4]; List nums = [.. numbers]; @@ -37,7 +36,7 @@ List nums = [.. numbers]; ```go title="list_test.go" /* 初始化列表 */ // 无初始值 -nums1 := []int{} +emptyNums := []int{} // 有初始值 nums := []int{1, 3, 2, 5, 4} ``` @@ -45,7 +44,7 @@ nums := []int{1, 3, 2, 5, 4} ```swift title="list.swift" /* 初始化列表 */ // 无初始值 -let nums1: [Int] = [] +let emptyNums: [Int] = [] // 有初始值 var nums = [1, 3, 2, 5, 4] ``` @@ -53,7 +52,7 @@ var nums = [1, 3, 2, 5, 4] ```javascript title="list.js" /* 初始化列表 */ // 无初始值 -const nums1 = []; +const emptyNums = []; // 有初始值 const nums = [1, 3, 2, 5, 4]; ``` @@ -61,7 +60,7 @@ const nums = [1, 3, 2, 5, 4]; ```typescript title="list.ts" /* 初始化列表 */ // 无初始值 -const nums1: number[] = []; +const emptyNums: number[] = []; // 有初始值 const nums: number[] = [1, 3, 2, 5, 4]; ``` @@ -69,15 +68,15 @@ const nums: number[] = [1, 3, 2, 5, 4]; ```dart title="list.dart" /* 初始化列表 */ // 无初始值 -List nums1 = []; +List emptyNums = []; // 有初始值 List nums = [1, 3, 2, 5, 4]; ``` ```rust title="list.rs" -/* 初始化列表 */ +// 初始化列表 // 无初始值 -let nums1: Vec = Vec::new(); +let empty_nums: Vec = Vec::new(); // 有初始值 let mut nums: Vec = vec![1, 3, 2, 5, 4]; ``` @@ -89,62 +88,61 @@ let mut nums: Vec = vec![1, 3, 2, 5, 4]; ```kotlin title="list.kt" /* 初始化列表 */ // 无初始值 -var nums1 = listOf() +val emptyNums = mutableListOf() // 有初始值 -var numbers = arrayOf(1, 3, 2, 5, 4) -var nums = numbers.toMutableList() +val nums = mutableListOf(1, 3, 2, 5, 4) ``` ```ruby title="list.rb" # 初始化列表 # 无初始值 -nums1 = [] +empty_nums = [] # 有初始值 nums = [1, 3, 2, 5, 4] ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20%23%20%E6%97%A0%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20%23%20%E6%97%A0%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20empty_nums%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" # 访问元素 -num: int = nums[1] # 访问索引 1 处的元素 +x: int = nums[1] # 访问索引 1 处的元素 # 更新元素 -nums[1] = 0 # 将索引 1 处的元素更新为 0 +nums[1] = 0 # 将索引 1 处的元素更新为 0 ``` ```cpp title="list.cpp" /* 访问元素 */ -int num = nums[1]; // 访问索引 1 处的元素 +int num = nums[1]; // 访问索引 1 处的元素 /* 更新元素 */ -nums[1] = 0; // 将索引 1 处的元素更新为 0 +nums[1] = 0; // 将索引 1 处的元素更新为 0 ``` ```java title="list.java" /* 访问元素 */ -int num = nums.get(1); // 访问索引 1 处的元素 +int num = nums.get(1); // 访问索引 1 处的元素 /* 更新元素 */ -nums.set(1, 0); // 将索引 1 处的元素更新为 0 +nums.set(1, 0); // 将索引 1 处的元素更新为 0 ``` ```csharp title="list.cs" /* 访问元素 */ -int num = nums[1]; // 访问索引 1 处的元素 +int num = nums[1]; // 访问索引 1 处的元素 /* 更新元素 */ -nums[1] = 0; // 将索引 1 处的元素更新为 0 +nums[1] = 0; // 将索引 1 处的元素更新为 0 ``` ```go title="list_test.go" /* 访问元素 */ -num := nums[1] // 访问索引 1 处的元素 +num := nums[1] // 访问索引 1 处的元素 /* 更新元素 */ -nums[1] = 0 // 将索引 1 处的元素更新为 0 +nums[1] = 0 // 将索引 1 处的元素更新为 0 ``` ```swift title="list.swift" @@ -157,33 +155,34 @@ nums[1] = 0 // 将索引 1 处的元素更新为 0 ```javascript title="list.js" /* 访问元素 */ -const num = nums[1]; // 访问索引 1 处的元素 +const num = nums[1]; // 访问索引 1 处的元素 /* 更新元素 */ -nums[1] = 0; // 将索引 1 处的元素更新为 0 +nums[1] = 0; // 将索引 1 处的元素更新为 0 ``` ```typescript title="list.ts" /* 访问元素 */ -const num: number = nums[1]; // 访问索引 1 处的元素 +const num: number = nums[1]; // 访问索引 1 处的元素 /* 更新元素 */ -nums[1] = 0; // 将索引 1 处的元素更新为 0 +nums[1] = 0; // 将索引 1 处的元素更新为 0 ``` ```dart title="list.dart" /* 访问元素 */ -int num = nums[1]; // 访问索引 1 处的元素 +int _num = nums[1]; // 访问索引 1 处的元素 /* 更新元素 */ -nums[1] = 0; // 将索引 1 处的元素更新为 0 +nums[1] = 0; // 将索引 1 处的元素更新为 0 ``` ```rust title="list.rs" -/* 访问元素 */ -let num: i32 = nums[1]; // 访问索引 1 处的元素 -/* 更新元素 */ -nums[1] = 0; // 将索引 1 处的元素更新为 0 +// 访问元素 +let num = nums[1]; // 访问索引 1 处的元素 + +// 更新元素 +nums[1] = 0; // 将索引 1 处的元素更新为 0 ``` ```c title="list.c" @@ -192,20 +191,22 @@ nums[1] = 0; // 将索引 1 处的元素更新为 0 ```kotlin title="list.kt" /* 访问元素 */ -val num = nums[1] // 访问索引 1 处的元素 +val num = nums[1] // 访问索引 1 处的元素 + /* 更新元素 */ -nums[1] = 0 // 将索引 1 处的元素更新为 0 +nums[1] = 0 // 将索引 1 处的元素更新为 0 ``` ```ruby title="list.rb" # 访问元素 num = nums[1] # 访问索引 1 处的元素 + # 更新元素 nums[1] = 0 # 将索引 1 处的元素更新为 0 ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E8%AE%BF%E9%97%AE%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%86%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E4%B8%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20x%20%3D%20nums%5B1%5D%20%20%23%20%E8%AE%BF%E9%97%AE%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%86%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E4%B8%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" @@ -223,7 +224,7 @@ nums.append(4) nums.insert(3, 6) # 在索引 3 处插入数字 6 # 删除元素 -nums.pop(3) # 删除索引 3 处的元素 +nums.pop(3) # 删除索引 3 处的元素 ``` ```cpp title="list.cpp" @@ -238,10 +239,10 @@ nums.push_back(5); nums.push_back(4); /* 在中间插入元素 */ -nums.insert(nums.begin() + 3, 6); // 在索引 3 处插入数字 6 +nums.insert(nums.begin() + 3, 6); // 在索引 3 处插入数字 6 /* 删除元素 */ -nums.erase(nums.begin() + 3); // 删除索引 3 处的元素 +nums.erase(nums.begin() + 3); // 删除索引 3 处的元素 ``` ```java title="list.java" @@ -256,10 +257,10 @@ nums.add(5); nums.add(4); /* 在中间插入元素 */ -nums.add(3, 6); // 在索引 3 处插入数字 6 +nums.add(3, 6); // 在索引 3 处插入数字 6 /* 删除元素 */ -nums.remove(3); // 删除索引 3 处的元素 +nums.remove(3); // 删除索引 3 处的元素 ``` ```csharp title="list.cs" @@ -274,10 +275,10 @@ nums.Add(5); nums.Add(4); /* 在中间插入元素 */ -nums.Insert(3, 6); // 在索引 3 处插入数字 6 +nums.Insert(3, 6); // 在索引 3 处插入数字 6 /* 删除元素 */ -nums.RemoveAt(3); // 删除索引 3 处的元素 +nums.RemoveAt(3); // 删除索引 3 处的元素 ``` ```go title="list_test.go" @@ -331,7 +332,7 @@ nums.push(4); nums.splice(3, 0, 6); // 在索引 3 处插入数字 6 /* 删除元素 */ -nums.splice(3, 1); // 删除索引 3 处的元素 +nums.splice(3, 1); // 删除索引 3 处的元素 ``` ```typescript title="list.ts" @@ -349,7 +350,7 @@ nums.push(4); nums.splice(3, 0, 6); // 在索引 3 处插入数字 6 /* 删除元素 */ -nums.splice(3, 1); // 删除索引 3 处的元素 +nums.splice(3, 1); // 删除索引 3 处的元素 ``` ```dart title="list.dart" @@ -371,21 +372,21 @@ nums.removeAt(3); // 删除索引 3 处的元素 ``` ```rust title="list.rs" -/* 清空列表 */ +// 清空列表 nums.clear(); -/* 在尾部添加元素 */ +// 在尾部添加元素 nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* 在中间插入元素 */ -nums.insert(3, 6); // 在索引 3 处插入数字 6 +// 在中间插入元素 +nums.insert(3, 6); // 在索引 3 处插入数字 6 -/* 删除元素 */ -nums.remove(3); // 删除索引 3 处的元素 +// 删除元素 +nums.remove(3); // 删除索引 3 处的元素 ``` ```c title="list.c" @@ -394,20 +395,20 @@ nums.remove(3); // 删除索引 3 处的元素 ```kotlin title="list.kt" /* 清空列表 */ -nums.clear(); +nums.clear() /* 在尾部添加元素 */ -nums.add(1); -nums.add(3); -nums.add(2); -nums.add(5); -nums.add(4); +nums.add(1) +nums.add(3) +nums.add(2) +nums.add(5) +nums.add(4) /* 在中间插入元素 */ -nums.add(3, 6); // 在索引 3 处插入数字 6 +nums.add(3, 6) // 在索引 3 处插入数字 6 /* 删除元素 */ -nums.removeAt(3); // 删除索引 3 处的元素 +nums.removeAt(3) // 删除索引 3 处的元素 ``` ```ruby title="list.rb" @@ -452,8 +453,8 @@ for (int i = 0; i < nums.size(); i++) { /* 直接遍历列表元素 */ count = 0; -for (int num : nums) { - count += num; +for (int x : nums) { + count += x; } ``` @@ -465,8 +466,8 @@ for (int i = 0; i < nums.size(); i++) { } /* 直接遍历列表元素 */ -for (int num : nums) { - count += num; +for (int x : nums) { + count += x; } ``` @@ -479,8 +480,8 @@ for (int i = 0; i < nums.Count; i++) { /* 直接遍历列表元素 */ count = 0; -foreach (int num in nums) { - count += num; +foreach (int x in nums) { + count += x; } ``` @@ -493,8 +494,8 @@ for i := 0; i < len(nums); i++ { /* 直接遍历列表元素 */ count = 0 -for _, num := range nums { - count += num +for _, x := range nums { + count += x } ``` @@ -507,8 +508,8 @@ for i in nums.indices { /* 直接遍历列表元素 */ count = 0 -for num in nums { - count += num +for x in nums { + count += x } ``` @@ -521,8 +522,8 @@ for (let i = 0; i < nums.length; i++) { /* 直接遍历列表元素 */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` @@ -535,8 +536,8 @@ for (let i = 0; i < nums.length; i++) { /* 直接遍历列表元素 */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` @@ -544,13 +545,13 @@ for (const num of nums) { /* 通过索引遍历列表 */ int count = 0; for (var i = 0; i < nums.length; i++) { - count += nums[i]; + count += nums[i]; } /* 直接遍历列表元素 */ count = 0; -for (var num in nums) { - count += num; +for (var x in nums) { + count += x; } ``` @@ -563,8 +564,8 @@ for i in 0..nums.len() { // 直接遍历列表元素 _count = 0; -for num in &nums { - _count += num; +for x in &nums { + _count += x; } ``` @@ -580,8 +581,8 @@ for (i in nums.indices) { } /* 直接遍历列表元素 */ -for (num in nums) { - count += num +for (j in nums) { + count += j } ``` @@ -589,13 +590,13 @@ for (num in nums) { # 通过索引遍历列表 count = 0 for i in 0...nums.length - count += nums[i] + count += nums[i] end # 直接遍历列表元素 count = 0 -for num in nums - count += num +nums.each do |x| + count += x end ``` @@ -605,13 +606,13 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 ```python title="list.py" # 拼接两个列表 -nums1: list[int] = [6, 8, 7, 10, 9] +nums1 = [6, 8, 7, 10, 9] nums += nums1 # 将列表 nums1 拼接到 nums 之后 ``` ```cpp title="list.cpp" /* 拼接两个列表 */ -vector nums1 = { 6, 8, 7, 10, 9 }; +vector nums1 = {6, 8, 7, 10, 9}; // 将列表 nums1 拼接到 nums 之后 nums.insert(nums.end(), nums1.begin(), nums1.end()); ``` @@ -619,19 +620,19 @@ nums.insert(nums.end(), nums1.begin(), nums1.end()); ```java title="list.java" /* 拼接两个列表 */ List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); -nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后 +nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后 ``` ```csharp title="list.cs" /* 拼接两个列表 */ List nums1 = [6, 8, 7, 10, 9]; -nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后 +nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后 ``` ```go title="list_test.go" /* 拼接两个列表 */ nums1 := []int{6, 8, 7, 10, 9} -nums = append(nums, nums1...) // 将列表 nums1 拼接到 nums 之后 +nums = append(nums, nums1...) // 将列表 nums1 拼接到 nums 之后 ``` ```swift title="list.swift" @@ -643,25 +644,25 @@ nums.append(contentsOf: nums1) // 将列表 nums1 拼接到 nums 之后 ```javascript title="list.js" /* 拼接两个列表 */ const nums1 = [6, 8, 7, 10, 9]; -nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后 +nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后 ``` ```typescript title="list.ts" /* 拼接两个列表 */ const nums1: number[] = [6, 8, 7, 10, 9]; -nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后 +nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后 ``` ```dart title="list.dart" /* 拼接两个列表 */ List nums1 = [6, 8, 7, 10, 9]; -nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后 +nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后 ``` ```rust title="list.rs" -/* 拼接两个列表 */ -let nums1: Vec = vec![6, 8, 7, 10, 9]; -nums.extend(nums1); +// 拼接两个列表 +let mut nums1 = vec![6, 8, 7, 10, 9]; +nums.append(&mut nums1); // append 会移走 nums1 的元素,之后 nums1 为空 ``` ```c title="list.c" @@ -670,8 +671,8 @@ nums.extend(nums1); ```kotlin title="list.kt" /* 拼接两个列表 */ -val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() -nums.addAll(nums1) // 将列表 nums1 拼接到 nums 之后 +val nums1 = mutableListOf(6, 8, 7, 10, 9) +nums.addAll(nums1) // 将列表 nums1 拼接到 nums 之后 ``` ```ruby title="list.rb" @@ -691,12 +692,12 @@ nums.sort() # 排序后,列表元素从小到大排列 ```cpp title="list.cpp" /* 排序列表 */ -sort(nums.begin(), nums.end()); // 排序后,列表元素从小到大排列 +sort(nums.begin(), nums.end()); // 排序后,列表元素从小到大排列 ``` ```java title="list.java" /* 排序列表 */ -Collections.sort(nums); // 排序后,列表元素从小到大排列 +Collections.sort(nums); // 排序后,列表元素从小到大排列 ``` ```csharp title="list.cs" @@ -706,7 +707,7 @@ nums.Sort(); // 排序后,列表元素从小到大排列 ```go title="list_test.go" /* 排序列表 */ -sort.Ints(nums) // 排序后,列表元素从小到大排列 +sort.Ints(nums) // 排序后,列表元素从小到大排列 ``` ```swift title="list.swift" @@ -716,12 +717,12 @@ nums.sort() // 排序后,列表元素从小到大排列 ```javascript title="list.js" /* 排序列表 */ -nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列 +nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列 ``` ```typescript title="list.ts" /* 排序列表 */ -nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列 +nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列 ``` ```dart title="list.dart" @@ -730,7 +731,7 @@ nums.sort(); // 排序后,列表元素从小到大排列 ``` ```rust title="list.rs" -/* 排序列表 */ +// 排序列表 nums.sort(); // 排序后,列表元素从小到大排列 ``` diff --git a/codes/snippets/chapter_hashing/hash_algorithm.md b/codes/snippets/chapter_hashing/hash_algorithm.md index 0e6a42f67..87ce9d5e2 100644 --- a/codes/snippets/chapter_hashing/hash_algorithm.md +++ b/codes/snippets/chapter_hashing/hash_algorithm.md @@ -2,44 +2,54 @@ ```python title="built_in_hash.py" num = 3 hash_num = hash(num) +print(f"整数 {num} 的哈希值为 {hash_num}") # 整数 3 的哈希值为 3 bol = True hash_bol = hash(bol) +print(f"布尔量 {bol} 的哈希值为 {hash_bol}") # 布尔量 True 的哈希值为 1 dec = 3.14159 hash_dec = hash(dec) +print(f"小数 {dec} 的哈希值为 {hash_dec}") # 小数 3.14159 的哈希值为 326484311674566659 str = "Hello 算法" hash_str = hash(str) +print(f"字符串“{str}”的哈希值为 {hash_str}") # 字符串“Hello 算法”的哈希值为 4617003410720528961 tup = (12836, "小哈") hash_tup = hash(tup) +print(f"元组 {tup} 的哈希值为 {hash_tup}") # 元组 (12836, '小哈') 的哈希值为 1029005403108185979 obj = ListNode(0) hash_obj = hash(obj) -# 节点对象 的哈希值为 274267521 +print(f"节点对象 {obj} 的哈希值为 {hash_obj}") +# 节点对象 的哈希值为 274267521 ``` ```cpp title="built_in_hash.cpp" int num = 3; size_t hashNum = hash()(num); +cout << "整数 " << num << " 的哈希值为 " << hashNum << "\n"; // 整数 3 的哈希值为 3 bool bol = true; size_t hashBol = hash()(bol); +cout << "布尔量 " << bol << " 的哈希值为 " << hashBol << "\n"; // 布尔量 1 的哈希值为 1 double dec = 3.14159; size_t hashDec = hash()(dec); +cout << "小数 " << dec << " 的哈希值为 " << hashDec << "\n"; // 小数 3.14159 的哈希值为 4614256650576692846 string str = "Hello 算法"; size_t hashStr = hash()(str); +cout << "字符串“" << str << "”的哈希值为 " << hashStr << "\n"; // 字符串“Hello 算法”的哈希值为 15466937326284535026 // 在 C++ 中,内置 std::hash() 仅提供基本数据类型的哈希值计算 @@ -49,53 +59,65 @@ size_t hashStr = hash()(str); ```java title="built_in_hash.java" int num = 3; int hashNum = Integer.hashCode(num); +System.out.println("整数 " + num + " 的哈希值为 " + hashNum); // 整数 3 的哈希值为 3 boolean bol = true; int hashBol = Boolean.hashCode(bol); +System.out.println("布尔量 " + bol + " 的哈希值为 " + hashBol); // 布尔量 true 的哈希值为 1231 double dec = 3.14159; int hashDec = Double.hashCode(dec); +System.out.println("小数 " + dec + " 的哈希值为 " + hashDec); // 小数 3.14159 的哈希值为 -1340954729 String str = "Hello 算法"; int hashStr = str.hashCode(); +System.out.println("字符串“" + str + "”的哈希值为 " + hashStr); // 字符串“Hello 算法”的哈希值为 -727081396 Object[] arr = { 12836, "小哈" }; -int hashTup = Arrays.hashCode(arr); +int hashArr = Arrays.hashCode(arr); +System.out.println("数组 " + Arrays.toString(arr) + " 的哈希值为 " + hashArr); // 数组 [12836, 小哈] 的哈希值为 1151158 ListNode obj = new ListNode(0); int hashObj = obj.hashCode(); +System.out.println("节点对象 " + obj + " 的哈希值为 " + hashObj); // 节点对象 utils.ListNode@7dc5e7b4 的哈希值为 2110121908 ``` ```csharp title="built_in_hash.cs" int num = 3; int hashNum = num.GetHashCode(); -// 整数 3 的哈希值为 3; +Console.WriteLine("整数 " + num + " 的哈希值为 " + hashNum); +// 整数 3 的哈希值为 3 bool bol = true; int hashBol = bol.GetHashCode(); -// 布尔量 true 的哈希值为 1; +Console.WriteLine("布尔量 " + bol + " 的哈希值为 " + hashBol); +// 布尔量 True 的哈希值为 1 double dec = 3.14159; int hashDec = dec.GetHashCode(); -// 小数 3.14159 的哈希值为 -1340954729; +Console.WriteLine("小数 " + dec + " 的哈希值为 " + hashDec); +// 小数 3.14159 的哈希值为 -1340954729 string str = "Hello 算法"; int hashStr = str.GetHashCode(); -// 字符串“Hello 算法”的哈希值为 -586107568; +Console.WriteLine("字符串“" + str + "”的哈希值为 " + hashStr); +// 字符串“Hello 算法”的哈希值为 -586107568 object[] arr = [12836, "小哈"]; -int hashTup = arr.GetHashCode(); -// 数组 [12836, 小哈] 的哈希值为 42931033; +int hashArr = arr.GetHashCode(); +Console.WriteLine("数组 [" + string.Join(", ", arr) + "] 的哈希值为 " + hashArr); +// 数组 [12836, 小哈] 的哈希值为 42931033 ListNode obj = new(0); int hashObj = obj.GetHashCode(); -// 节点对象 0 的哈希值为 39053774; +Console.WriteLine("节点对象 " + obj + " 的哈希值为 " + hashObj); +// 节点对象 0 的哈希值为 39053774 ``` ```go title="built_in_hash.go" @@ -105,26 +127,32 @@ int hashObj = obj.GetHashCode(); ```swift title="built_in_hash.swift" let num = 3 let hashNum = num.hashValue +print("整数 \(num) 的哈希值为 \(hashNum)") // 整数 3 的哈希值为 9047044699613009734 let bol = true let hashBol = bol.hashValue +print("布尔量 \(bol) 的哈希值为 \(hashBol)") // 布尔量 true 的哈希值为 -4431640247352757451 let dec = 3.14159 let hashDec = dec.hashValue +print("小数 \(dec) 的哈希值为 \(hashDec)") // 小数 3.14159 的哈希值为 -2465384235396674631 let str = "Hello 算法" let hashStr = str.hashValue +print("字符串“\(str)”的哈希值为 \(hashStr)") // 字符串“Hello 算法”的哈希值为 -7850626797806988787 let arr = [AnyHashable(12836), AnyHashable("小哈")] -let hashTup = arr.hashValue +let hashArr = arr.hashValue +print("数组 \(arr) 的哈希值为 \(hashArr)") // 数组 [AnyHashable(12836), AnyHashable("小哈")] 的哈希值为 -2308633508154532996 let obj = ListNode(x: 0) let hashObj = obj.hashValue +print("节点对象 \(obj) 的哈希值为 \(hashObj)") // 节点对象 utils.ListNode 的哈希值为 -2434780518035996159 ``` @@ -139,26 +167,32 @@ let hashObj = obj.hashValue ```dart title="built_in_hash.dart" int num = 3; int hashNum = num.hashCode; +print("整数 $num 的哈希值为 $hashNum"); // 整数 3 的哈希值为 34803 bool bol = true; int hashBol = bol.hashCode; -// 布尔值 true 的哈希值为 1231 +print("布尔量 $bol 的哈希值为 $hashBol"); +// 布尔量 true 的哈希值为 1231 double dec = 3.14159; int hashDec = dec.hashCode; +print("小数 $dec 的哈希值为 $hashDec"); // 小数 3.14159 的哈希值为 2570631074981783 String str = "Hello 算法"; int hashStr = str.hashCode; +print("字符串“$str”的哈希值为 $hashStr"); // 字符串“Hello 算法”的哈希值为 468167534 List arr = [12836, "小哈"]; int hashArr = arr.hashCode; +print("数组 $arr 的哈希值为 $hashArr"); // 数组 [12836, 小哈] 的哈希值为 976512528 -ListNode obj = new ListNode(0); +ListNode obj = ListNode(0); int hashObj = obj.hashCode; +print("节点对象 $obj 的哈希值为 $hashObj"); // 节点对象 Instance of 'ListNode' 的哈希值为 1033450432 ``` @@ -170,37 +204,43 @@ let num = 3; let mut num_hasher = DefaultHasher::new(); num.hash(&mut num_hasher); let hash_num = num_hasher.finish(); +println!("整数 {} 的哈希值为 {}", num, hash_num); // 整数 3 的哈希值为 568126464209439262 let bol = true; let mut bol_hasher = DefaultHasher::new(); bol.hash(&mut bol_hasher); let hash_bol = bol_hasher.finish(); +println!("布尔量 {} 的哈希值为 {}", bol, hash_bol); // 布尔量 true 的哈希值为 4952851536318644461 let dec: f32 = 3.14159; let mut dec_hasher = DefaultHasher::new(); dec.to_bits().hash(&mut dec_hasher); let hash_dec = dec_hasher.finish(); +println!("小数 {} 的哈希值为 {}", dec, hash_dec); // 小数 3.14159 的哈希值为 2566941990314602357 let str = "Hello 算法"; let mut str_hasher = DefaultHasher::new(); str.hash(&mut str_hasher); let hash_str = str_hasher.finish(); +println!("字符串“{}”的哈希值为 {}", str, hash_str); // 字符串“Hello 算法”的哈希值为 16092673739211250988 -let arr = (&12836, &"小哈"); +let tup = (&12836, &"小哈"); let mut tup_hasher = DefaultHasher::new(); -arr.hash(&mut tup_hasher); +tup.hash(&mut tup_hasher); let hash_tup = tup_hasher.finish(); +println!("元组 {:?} 的哈希值为 {}", tup, hash_tup); // 元组 (12836, "小哈") 的哈希值为 1885128010422702749 let node = ListNode::new(42); -let mut hasher = DefaultHasher::new(); -node.borrow().val.hash(&mut hasher); -let hash = hasher.finish(); -// 节点对象 RefCell { value: ListNode { val: 42, next: None } } 的哈希值为15387811073369036852 +let mut node_hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut node_hasher); +let hash_node = node_hasher.finish(); +println!("节点对象 {:?} 的哈希值为 {}", node, hash_node); +// 节点对象 RefCell { value: ListNode { val: 42, next: None } } 的哈希值为 15387811073369036852 ``` ```c title="built_in_hash.c" @@ -210,54 +250,66 @@ let hash = hasher.finish(); ```kotlin title="built_in_hash.kt" val num = 3 val hashNum = num.hashCode() +println("整数 $num 的哈希值为 $hashNum") // 整数 3 的哈希值为 3 val bol = true val hashBol = bol.hashCode() +println("布尔量 $bol 的哈希值为 $hashBol") // 布尔量 true 的哈希值为 1231 val dec = 3.14159 val hashDec = dec.hashCode() +println("小数 $dec 的哈希值为 $hashDec") // 小数 3.14159 的哈希值为 -1340954729 val str = "Hello 算法" val hashStr = str.hashCode() +println("字符串“$str”的哈希值为 $hashStr") // 字符串“Hello 算法”的哈希值为 -727081396 val arr = arrayOf(12836, "小哈") -val hashTup = arr.hashCode() -// 数组 [12836, 小哈] 的哈希值为 189568618 +val hashArr = arr.contentHashCode() +println("数组 ${arr.contentToString()} 的哈希值为 $hashArr") +// 数组 [12836, 小哈] 的哈希值为 1151158 val obj = ListNode(0) val hashObj = obj.hashCode() +println("节点对象 $obj 的哈希值为 $hashObj") // 节点对象 utils.ListNode@1d81eb93 的哈希值为 495053715 ``` ```ruby title="built_in_hash.rb" num = 3 hash_num = num.hash +puts "整数 #{num} 的哈希值为 #{hash_num}" # 整数 3 的哈希值为 -4385856518450339636 bol = true hash_bol = bol.hash +puts "布尔量 #{bol} 的哈希值为 #{hash_bol}" # 布尔量 true 的哈希值为 -1617938112149317027 dec = 3.14159 hash_dec = dec.hash +puts "小数 #{dec} 的哈希值为 #{hash_dec}" # 小数 3.14159 的哈希值为 -1479186995943067893 str = "Hello 算法" hash_str = str.hash +puts "字符串“#{str}”的哈希值为 #{hash_str}" # 字符串“Hello 算法”的哈希值为 -4075943250025831763 -tup = [12836, '小哈'] -hash_tup = tup.hash -# 元组 (12836, '小哈') 的哈希值为 1999544809202288822 +arr = [12836, '小哈'] +hash_arr = arr.hash +puts "数组 #{arr} 的哈希值为 #{hash_arr}" +# 数组 [12836, "小哈"] 的哈希值为 1999544809202288822 obj = ListNode.new(0) hash_obj = obj.hash +puts "节点对象 #{obj} 的哈希值为 #{hash_obj}" # 节点对象 # 的哈希值为 4302940560806366381 ``` -https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%E5%B8%83%E5%B0%94%E9%87%8F%20True%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%E5%AD%97%E7%AC%A6%E4%B8%B2%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836,%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%E5%85%83%E7%BB%84%20%2812836,%20'%E5%B0%8F%E5%93%88'%29%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%AF%B9%E8%B1%A1%20%3CListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20print%28f%22%E6%95%B4%E6%95%B0%20%7Bnum%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_num%7D%22%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20print%28f%22%E5%B8%83%E5%B0%94%E9%87%8F%20%7Bbol%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_bol%7D%22%29%0A%20%20%20%20%23%20%E5%B8%83%E5%B0%94%E9%87%8F%20True%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20print%28f%22%E5%B0%8F%E6%95%B0%20%7Bdec%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_dec%7D%22%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20print%28f%22%E5%AD%97%E7%AC%A6%E4%B8%B2%E2%80%9C%7Bstr%7D%E2%80%9D%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_str%7D%22%29%0A%20%20%20%20%23%20%E5%AD%97%E7%AC%A6%E4%B8%B2%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836,%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20print%28f%22%E5%85%83%E7%BB%84%20%7Btup%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_tup%7D%22%29%0A%20%20%20%20%23%20%E5%85%83%E7%BB%84%20%2812836,%20%27%E5%B0%8F%E5%93%88%27%29%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20print%28f%22%E8%8A%82%E7%82%B9%E5%AF%B9%E8%B1%A1%20%7Bobj%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_obj%7D%22%29%0A%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%AF%B9%E8%B1%A1%20%3Cmodules.list_node.ListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20274267521%0A&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_hashing/hash_map.md b/codes/snippets/chapter_hashing/hash_map.md index f8ae2ad72..2e90a99f8 100644 --- a/codes/snippets/chapter_hashing/hash_map.md +++ b/codes/snippets/chapter_hashing/hash_map.md @@ -1,7 +1,7 @@ ```python title="hash_map.py" # 初始化哈希表 -hmap: dict = {} +hmap = dict[int, str]() # 添加操作 # 在哈希表中添加键值对 (key, value) @@ -128,6 +128,7 @@ map.removeValue(forKey: 10583) ```javascript title="hash_map.js" /* 初始化哈希表 */ const map = new Map(); + /* 添加操作 */ // 在哈希表中添加键值对 (key, value) map.set(12836, '小哈'); @@ -148,6 +149,7 @@ map.delete(10583); ```typescript title="hash_map.ts" /* 初始化哈希表 */ const map = new Map(); + /* 添加操作 */ // 在哈希表中添加键值对 (key, value) map.set(12836, '小哈'); @@ -155,24 +157,19 @@ map.set(15937, '小啰'); map.set(16750, '小算'); map.set(13276, '小法'); map.set(10583, '小鸭'); -console.info('\n添加完成后,哈希表为\nKey -> Value'); -console.info(map); /* 查询操作 */ // 向哈希表中输入键 key ,得到值 value let name = map.get(15937); -console.info('\n输入学号 15937 ,查询到姓名 ' + name); /* 删除操作 */ // 在哈希表中删除键值对 (key, value) map.delete(10583); -console.info('\n删除 10583 后,哈希表为\nKey -> Value'); -console.info(map); ``` ```dart title="hash_map.dart" /* 初始化哈希表 */ -Map map = {}; +final Map map = {}; /* 添加操作 */ // 在哈希表中添加键值对 (key, value) @@ -184,7 +181,7 @@ map[10583] = "小鸭"; /* 查询操作 */ // 向哈希表中输入键 key ,得到值 value -String? name = map[15937]; +final String? name = map[15937]; /* 删除操作 */ // 在哈希表中删除键值对 (key, value) @@ -194,24 +191,24 @@ map.remove(10583); ```rust title="hash_map.rs" use std::collections::HashMap; -/* 初始化哈希表 */ -let mut map: HashMap = HashMap::new(); +// 初始化哈希表 +let mut map = HashMap::new(); -/* 添加操作 */ +// 添加操作 // 在哈希表中添加键值对 (key, value) -map.insert(12836, "小哈".to_string()); -map.insert(15937, "小啰".to_string()); -map.insert(16750, "小算".to_string()); -map.insert(13276, "小法".to_string()); -map.insert(10583, "小鸭".to_string()); +map.insert(12836, "小哈"); +map.insert(15937, "小啰"); +map.insert(16750, "小算"); +map.insert(13276, "小法"); +map.insert(10583, "小鸭"); -/* 查询操作 */ +// 查询操作 // 向哈希表中输入键 key ,得到值 value -let _name: Option<&String> = map.get(&15937); +let name = map.get(&15937).copied().unwrap(); -/* 删除操作 */ +// 删除操作 // 在哈希表中删除键值对 (key, value) -let _removed_value: Option = map.remove(&10583); +_ = map.remove(&10583); ``` ```c title="hash_map.c" @@ -220,7 +217,7 @@ let _removed_value: Option = map.remove(&10583); ```kotlin title="hash_map.kt" /* 初始化哈希表 */ -val map = HashMap() +val map = HashMap() /* 添加操作 */ // 在哈希表中添加键值对 (key, value) @@ -269,52 +266,59 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 # 遍历键值对 key->value for key, value in hmap.items(): print(key, "->", value) + # 单独遍历键 key for key in hmap.keys(): print(key) + # 单独遍历值 value -for value in hmap.values(): - print(value) +for val in hmap.values(): + print(val) ``` ```cpp title="hash_map.cpp" /* 遍历哈希表 */ // 遍历键值对 key->value -for (auto kv: map) { +for (auto kv : map) { cout << kv.first << " -> " << kv.second << endl; } + // 使用迭代器遍历 key->value for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; + cout << iter->first << " -> " << iter->second << endl; } ``` ```java title="hash_map.java" /* 遍历哈希表 */ // 遍历键值对 key->value -for (Map.Entry kv: map.entrySet()) { +for (Map.Entry kv : map.entrySet()) { System.out.println(kv.getKey() + " -> " + kv.getValue()); } + // 单独遍历键 key -for (int key: map.keySet()) { +for (int key : map.keySet()) { System.out.println(key); } + // 单独遍历值 value -for (String val: map.values()) { +for (String val : map.values()) { System.out.println(val); } ``` ```csharp title="hash_map.cs" /* 遍历哈希表 */ -// 遍历键值对 Key->Value +// 遍历键值对 key->value foreach (var kv in map) { Console.WriteLine(kv.Key + " -> " + kv.Value); } + // 单独遍历键 key foreach (int key in map.Keys) { Console.WriteLine(key); } + // 单独遍历值 value foreach (string val in map.Values) { Console.WriteLine(val); @@ -327,10 +331,12 @@ foreach (string val in map.Values) { for key, value := range hmap { fmt.Println(key, "->", value) } + // 单独遍历键 key for key := range hmap { fmt.Println(key) } + // 单独遍历值 value for _, value := range hmap { fmt.Println(value) @@ -339,15 +345,17 @@ for _, value := range hmap { ```swift title="hash_map.swift" /* 遍历哈希表 */ -// 遍历键值对 Key->Value +// 遍历键值对 key->value for (key, value) in map { print("\(key) -> \(value)") } -// 单独遍历键 Key + +// 单独遍历键 key for key in map.keys { print(key) } -// 单独遍历值 Value + +// 单独遍历值 value for value in map.values { print(value) } @@ -355,15 +363,17 @@ for value in map.values { ```javascript title="hash_map.js" /* 遍历哈希表 */ -console.info('\n遍历键值对 Key->Value'); +// 遍历键值对 key->value for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\n单独遍历键 Key'); + +// 单独遍历键 key for (const k of map.keys()) { console.info(k); } -console.info('\n单独遍历值 Value'); + +// 单独遍历值 value for (const v of map.values()) { console.info(v); } @@ -371,15 +381,17 @@ for (const v of map.values()) { ```typescript title="hash_map.ts" /* 遍历哈希表 */ -console.info('\n遍历键值对 Key->Value'); +// 遍历键值对 key->value for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\n单独遍历键 Key'); + +// 单独遍历键 key for (const k of map.keys()) { console.info(k); } -console.info('\n单独遍历值 Value'); + +// 单独遍历值 value for (const v of map.values()) { console.info(v); } @@ -387,35 +399,29 @@ for (const v of map.values()) { ```dart title="hash_map.dart" /* 遍历哈希表 */ -// 遍历键值对 Key->Value -map.forEach((key, value) { - print('$key -> $value'); -}); +// 遍历键值对 key->value +map.forEach((key, value) => print("$key -> $value")); -// 单独遍历键 Key -map.keys.forEach((key) { - print(key); -}); +// 单独遍历键 key +map.keys.forEach((key) => print(key)); -// 单独遍历值 Value -map.values.forEach((value) { - print(value); -}); +// 单独遍历值 value +map.values.forEach((value) => print(value)); ``` ```rust title="hash_map.rs" -/* 遍历哈希表 */ -// 遍历键值对 Key->Value +// 遍历哈希表 +// 遍历键值对 key->value for (key, value) in &map { println!("{key} -> {value}"); } -// 单独遍历键 Key +// 单独遍历键 key for key in map.keys() { println!("{key}"); } -// 单独遍历值 Value +// 单独遍历值 value for value in map.values() { println!("{value}"); } @@ -431,10 +437,12 @@ for value in map.values() { for ((key, value) in map) { println("$key -> $value") } + // 单独遍历键 key for (key in map.keys) { println(key) } + // 单独遍历值 value for (_val in map.values) { println(_val) @@ -454,4 +462,4 @@ hmap.values.each { |val| puts val } ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B7%BB%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E9%94%AE%E5%80%BC%E5%AF%B9%20key-%3Evalue%0A%20%20%20%20for%20key,%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key,%20%22-%3E%22,%20value%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E9%94%AE%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E5%80%BC%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B7%BB%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E9%94%AE%E5%80%BC%E5%AF%B9%20key-%3Evalue%0A%20%20%20%20for%20key,%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key,%20%22-%3E%22,%20value%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E9%94%AE%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E5%80%BC%20value%0A%20%20%20%20for%20val%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28val%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_heap/heap.md b/codes/snippets/chapter_heap/heap.md index e02b5332e..78a2bea9b 100644 --- a/codes/snippets/chapter_heap/heap.md +++ b/codes/snippets/chapter_heap/heap.md @@ -17,15 +17,15 @@ heapq.heappush(max_heap, flag * 5) heapq.heappush(max_heap, flag * 4) # 获取堆顶元素 -peek: int = flag * max_heap[0] # 5 +peek: int = flag * max_heap[0] # 5 # 堆顶元素出堆 # 出堆元素会形成一个从大到小的序列 -val = flag * heapq.heappop(max_heap) # 5 -val = flag * heapq.heappop(max_heap) # 4 -val = flag * heapq.heappop(max_heap) # 3 -val = flag * heapq.heappop(max_heap) # 2 -val = flag * heapq.heappop(max_heap) # 1 +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 # 获取堆大小 size: int = len(max_heap) @@ -34,6 +34,7 @@ size: int = len(max_heap) is_empty: bool = not max_heap # 输入列表并建堆 +# 时间复杂度为 O(n) ,而非 O(nlogn) min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) ``` @@ -70,6 +71,7 @@ int size = maxHeap.size(); bool isEmpty = maxHeap.empty(); /* 输入列表并建堆 */ +// 时间复杂度为 O(n) ,而非 O(nlogn) vector input{1, 3, 2, 5, 4}; minHeap = priority_queue, greater>(input.begin(), input.end()); ``` @@ -106,6 +108,7 @@ int size = maxHeap.size(); boolean isEmpty = maxHeap.isEmpty(); /* 输入列表并建堆 */ +// 时间复杂度为 O(n) ,而非 O(nlogn) minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); ``` @@ -124,15 +127,15 @@ maxHeap.Enqueue(5, 5); maxHeap.Enqueue(4, 4); /* 获取堆顶元素 */ -int peek = maxHeap.Peek();//5 +int peek = maxHeap.Peek(); // 5 /* 堆顶元素出堆 */ // 出堆元素会形成一个从大到小的序列 -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 /* 获取堆大小 */ int size = maxHeap.Count; @@ -141,6 +144,7 @@ int size = maxHeap.Count; bool isEmpty = maxHeap.Count == 0; /* 输入列表并建堆 */ +// 时间复杂度为 O(n) ,而非 O(nlogn) minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); ``` @@ -149,14 +153,14 @@ minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); // 实现 heap.Interface 需要同时实现 sort.Interface type intHeap []any -// Push heap.Interface 的方法,实现推入元素到堆 +// Push heap.Interface 的函数,实现推入元素到堆 func (h *intHeap) Push(x any) { // Push 和 Pop 使用 pointer receiver 作为参数 // 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。 *h = append(*h, x.(int)) } -// Pop heap.Interface 的方法,实现弹出堆顶元素 +// Pop heap.Interface 的函数,实现弹出堆顶元素 func (h *intHeap) Pop() any { // 待出堆元素存放在最后 last := (*h)[len(*h)-1] @@ -164,18 +168,18 @@ func (h *intHeap) Pop() any { return last } -// Len sort.Interface 的方法 +// Len sort.Interface 的函数 func (h *intHeap) Len() int { return len(*h) } -// Less sort.Interface 的方法 +// Less sort.Interface 的函数 func (h *intHeap) Less(i, j int) bool { // 如果实现小顶堆,则需要调整为小于号 return (*h)[i].(int) > (*h)[j].(int) } -// Swap sort.Interface 的方法 +// Swap sort.Interface 的函数 func (h *intHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } @@ -185,31 +189,31 @@ func (h *intHeap) Top() any { return (*h)[0] } -/* Driver Code */ func TestHeap(t *testing.T) { /* 初始化堆 */ // 初始化大顶堆 maxHeap := &intHeap{} heap.Init(maxHeap) /* 元素入堆 */ - // 调用 heap.Interface 的方法,来添加元素 + // 调用 heap.Interface 的函数,来添加元素 heap.Push(maxHeap, 1) heap.Push(maxHeap, 3) heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) /* 获取堆顶元素 */ top := maxHeap.Top() fmt.Printf("堆顶元素为 %d\n", top) /* 堆顶元素出堆 */ - // 调用 heap.Interface 的方法,来移除元素 - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 + // 调用 heap.Interface 的函数,来移除元素 + fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 5 + fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 4 + fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 3 + fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 2 + fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 1 /* 获取堆大小 */ size := len(*maxHeap) @@ -222,8 +226,10 @@ func TestHeap(t *testing.T) { ``` ```swift title="heap.swift" +import HeapModule + /* 初始化堆 */ -// Swift 的 Heap 类型同时支持最大堆和最小堆,且需要引入 swift-collections +// Swift 的 Heap 类型同时支持大顶堆和小顶堆,需要引入 swift-collections 包 var heap = Heap() /* 元素入堆 */ @@ -234,7 +240,7 @@ heap.insert(5) heap.insert(4) /* 获取堆顶元素 */ -var peek = heap.max()! +var peek = heap.max() /* 堆顶元素出堆 */ peek = heap.removeMax() // 5 @@ -250,6 +256,7 @@ let size = heap.count let isEmpty = heap.isEmpty /* 输入列表并建堆 */ +// 时间复杂度为 O(n) ,而非 O(nlogn) let heap2 = Heap([1, 3, 2, 5, 4]) ``` @@ -266,12 +273,13 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +use std::{cmp::Reverse, collections::BinaryHeap}; /* 初始化堆 */ // 初始化小顶堆 -let mut min_heap = BinaryHeap::>::new(); +// Rust 的 BinaryHeap 是大顶堆,小顶堆需用 Reverse 包装元素 +#[allow(unused_assignments)] +let mut min_heap = BinaryHeap::new(); // 初始化大顶堆 let mut max_heap = BinaryHeap::new(); @@ -283,15 +291,15 @@ max_heap.push(5); max_heap.push(4); /* 获取堆顶元素 */ -let peek = max_heap.peek().unwrap(); // 5 +let peek = max_heap.peek().unwrap(); // 5 /* 堆顶元素出堆 */ // 出堆元素会形成一个从大到小的序列 -let peek = max_heap.pop().unwrap(); // 5 -let peek = max_heap.pop().unwrap(); // 4 -let peek = max_heap.pop().unwrap(); // 3 -let peek = max_heap.pop().unwrap(); // 2 -let peek = max_heap.pop().unwrap(); // 1 +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 /* 获取堆大小 */ let size = max_heap.len(); @@ -300,7 +308,8 @@ let size = max_heap.len(); let is_empty = max_heap.is_empty(); /* 输入列表并建堆 */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +// 时间复杂度为 O(n) ,而非 O(nlogn) +min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); ``` ```c title="heap.c" @@ -339,7 +348,8 @@ val size = maxHeap.size val isEmpty = maxHeap.isEmpty() /* 输入列表并建堆 */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +// 时间复杂度为 O(n) ,而非 O(nlogn) +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` ```ruby title="heap.rb" @@ -347,4 +357,4 @@ minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` -https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20min_heap,%20flag%20%3D%20%5B%5D,%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20max_heap,%20flag%20%3D%20%5B%5D,%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E5%9D%97%E9%BB%98%E8%AE%A4%E5%AE%9E%E7%8E%B0%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E8%80%83%E8%99%91%E5%B0%86%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B4%9F%E2%80%9D%E5%90%8E%E5%86%8D%E5%85%A5%E5%A0%86%EF%BC%8C%E8%BF%99%E6%A0%B7%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%86%E5%A4%A7%E5%B0%8F%E5%85%B3%E7%B3%BB%E9%A2%A0%E5%80%92%EF%BC%8C%E4%BB%8E%E8%80%8C%E5%AE%9E%E7%8E%B0%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%B0%8F%E9%A1%B6%E5%A0%86%EF%BC%8Cflag%20%3D%20-1%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%201%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%203%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%202%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%205%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20*%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E5%85%83%E7%B4%A0%E4%BC%9A%E5%BD%A2%E6%88%90%E4%B8%80%E4%B8%AA%E4%BB%8E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E5%A0%86%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BE%93%E5%85%A5%E5%88%97%E8%A1%A8%E5%B9%B6%E5%BB%BA%E5%A0%86%0A%20%20%20%20min_heap%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20min_heap,%20flag%20%3D%20%5B%5D,%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20max_heap,%20flag%20%3D%20%5B%5D,%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E5%9D%97%E9%BB%98%E8%AE%A4%E5%AE%9E%E7%8E%B0%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E8%80%83%E8%99%91%E5%B0%86%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B4%9F%E2%80%9D%E5%90%8E%E5%86%8D%E5%85%A5%E5%A0%86%EF%BC%8C%E8%BF%99%E6%A0%B7%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%86%E5%A4%A7%E5%B0%8F%E5%85%B3%E7%B3%BB%E9%A2%A0%E5%80%92%EF%BC%8C%E4%BB%8E%E8%80%8C%E5%AE%9E%E7%8E%B0%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%B0%8F%E9%A1%B6%E5%A0%86%EF%BC%8Cflag%20%3D%20-1%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E5%85%83%E7%B4%A0%E4%BC%9A%E5%BD%A2%E6%88%90%E4%B8%80%E4%B8%AA%E4%BB%8E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E5%A0%86%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BE%93%E5%85%A5%E5%88%97%E8%A1%A8%E5%B9%B6%E5%BB%BA%E5%A0%86%0A%20%20%20%20%23%20%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6%E4%B8%BA%20O%28n%29%20%EF%BC%8C%E8%80%8C%E9%9D%9E%20O%28nlogn%29%0A%20%20%20%20min_heap%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/snippets/chapter_stack_and_queue/deque.md b/codes/snippets/chapter_stack_and_queue/deque.md index 1f4d203d3..ffd3f77cc 100644 --- a/codes/snippets/chapter_stack_and_queue/deque.md +++ b/codes/snippets/chapter_stack_and_queue/deque.md @@ -6,7 +6,7 @@ from collections import deque deq: deque[int] = deque() # 元素入队 -deq.append(2) # 添加至队尾 +deq.append(2) # 添加至队尾 deq.append(5) deq.append(4) deq.appendleft(3) # 添加至队首 @@ -18,7 +18,7 @@ rear: int = deq[-1] # 队尾元素 # 元素出队 pop_front: int = deq.popleft() # 队首元素出队 -pop_rear: int = deq.pop() # 队尾元素出队 +pop_rear: int = deq.pop() # 队尾元素出队 # 获取双向队列的长度 size: int = len(deq) @@ -32,19 +32,19 @@ is_empty: bool = len(deq) == 0 deque deque; /* 元素入队 */ -deque.push_back(2); // 添加至队尾 +deque.push_back(2); // 添加至队尾 deque.push_back(5); deque.push_back(4); -deque.push_front(3); // 添加至队首 +deque.push_front(3); // 添加至队首 deque.push_front(1); /* 访问元素 */ int front = deque.front(); // 队首元素 -int back = deque.back(); // 队尾元素 +int back = deque.back(); // 队尾元素 /* 元素出队 */ -deque.pop_front(); // 队首元素出队 -deque.pop_back(); // 队尾元素出队 +deque.pop_front(); // 队首元素出队 +deque.pop_back(); // 队尾元素出队 /* 获取双向队列的长度 */ int size = deque.size(); @@ -58,19 +58,19 @@ bool empty = deque.empty(); Deque deque = new LinkedList<>(); /* 元素入队 */ -deque.offerLast(2); // 添加至队尾 +deque.offerLast(2); // 添加至队尾 deque.offerLast(5); deque.offerLast(4); -deque.offerFirst(3); // 添加至队首 +deque.offerFirst(3); // 添加至队首 deque.offerFirst(1); /* 访问元素 */ -int peekFirst = deque.peekFirst(); // 队首元素 -int peekLast = deque.peekLast(); // 队尾元素 +int peekFirst = deque.peekFirst(); // 队首元素 +int peekLast = deque.peekLast(); // 队尾元素 /* 元素出队 */ -int popFirst = deque.pollFirst(); // 队首元素出队 -int popLast = deque.pollLast(); // 队尾元素出队 +int popFirst = deque.pollFirst(); // 队首元素出队 +int popLast = deque.pollLast(); // 队尾元素出队 /* 获取双向队列的长度 */ int size = deque.size(); @@ -81,7 +81,7 @@ boolean isEmpty = deque.isEmpty(); ```csharp title="deque.cs" /* 初始化双向队列 */ -// 在 C# 中,将链表 LinkedList 看作双向队列来使用 +// 在 C# 中,将链表 LinkedList 当作双向队列来使用 LinkedList deque = new(); /* 元素入队 */ @@ -92,8 +92,8 @@ deque.AddFirst(3); // 添加至队首 deque.AddFirst(1); /* 访问元素 */ -int peekFirst = deque.First.Value; // 队首元素 -int peekLast = deque.Last.Value; // 队尾元素 +int? peekFirst = deque.First?.Value; // 队首元素 +int? peekLast = deque.Last?.Value; // 队尾元素 /* 元素出队 */ deque.RemoveFirst(); // 队首元素出队 @@ -112,19 +112,19 @@ bool isEmpty = deque.Count == 0; deque := list.New() /* 元素入队 */ -deque.PushBack(2) // 添加至队尾 +deque.PushBack(2) // 添加至队尾 deque.PushBack(5) deque.PushBack(4) -deque.PushFront(3) // 添加至队首 +deque.PushFront(3) // 添加至队首 deque.PushFront(1) /* 访问元素 */ front := deque.Front() // 队首元素 -rear := deque.Back() // 队尾元素 +rear := deque.Back() // 队尾元素 /* 元素出队 */ -deque.Remove(front) // 队首元素出队 -deque.Remove(rear) // 队尾元素出队 +deque.Remove(front) // 队首元素出队 +deque.Remove(rear) // 队尾元素出队 /* 获取双向队列的长度 */ size := deque.Len() @@ -150,7 +150,7 @@ let peekFirst = deque.first! // 队首元素 let peekLast = deque.last! // 队尾元素 /* 元素出队 */ -// 使用 Array 模拟时 popFirst 的复杂度为 O(n) +// 使用 Array 模拟时 removeFirst 的复杂度为 O(n) let popFirst = deque.removeFirst() // 队首元素出队 let popLast = deque.removeLast() // 队尾元素出队 @@ -222,57 +222,53 @@ const isEmpty: boolean = size === 0; ```dart title="deque.dart" /* 初始化双向队列 */ // 在 Dart 中,Queue 被定义为双向队列 -Queue deque = Queue(); +final Queue deque = Queue(); /* 元素入队 */ -deque.addLast(2); // 添加至队尾 +deque.addLast(2); // 添加至队尾 deque.addLast(5); deque.addLast(4); deque.addFirst(3); // 添加至队首 deque.addFirst(1); /* 访问元素 */ -int peekFirst = deque.first; // 队首元素 -int peekLast = deque.last; // 队尾元素 +final int peekFirst = deque.first; // 队首元素 +final int peekLast = deque.last; // 队尾元素 /* 元素出队 */ -int popFirst = deque.removeFirst(); // 队首元素出队 -int popLast = deque.removeLast(); // 队尾元素出队 +final int popFirst = deque.removeFirst(); // 队首元素出队 +final int popLast = deque.removeLast(); // 队尾元素出队 /* 获取双向队列的长度 */ -int size = deque.length; +final int size = deque.length; /* 判断双向队列是否为空 */ -bool isEmpty = deque.isEmpty; +final bool isEmpty = deque.isEmpty; ``` ```rust title="deque.rs" -/* 初始化双向队列 */ -let mut deque: VecDeque = VecDeque::new(); +// 初始化双向队列 +let mut deque: VecDeque = VecDeque::new(); /* 元素入队 */ -deque.push_back(2); // 添加至队尾 +deque.push_back(2); // 添加至队尾 deque.push_back(5); deque.push_back(4); deque.push_front(3); // 添加至队首 deque.push_front(1); -/* 访问元素 */ -if let Some(front) = deque.front() { // 队首元素 -} -if let Some(rear) = deque.back() { // 队尾元素 -} +// 访问元素 +let peek_first = deque.front().unwrap(); // 队首元素 +let peek_last = deque.back().unwrap(); // 队尾元素 -/* 元素出队 */ -if let Some(pop_front) = deque.pop_front() { // 队首元素出队 -} -if let Some(pop_rear) = deque.pop_back() { // 队尾元素出队 -} +// 元素出队 +let pop_first = deque.pop_front().unwrap(); // 队首元素出队 +let pop_last = deque.pop_back().unwrap(); // 队尾元素出队 -/* 获取双向队列的长度 */ +// 获取双向队列的长度 let size = deque.len(); -/* 判断双向队列是否为空 */ +// 判断双向队列是否为空 let is_empty = deque.is_empty(); ``` @@ -285,7 +281,7 @@ let is_empty = deque.is_empty(); val deque = LinkedList() /* 元素入队 */ -deque.offerLast(2) // 添加至队尾 +deque.offerLast(2) // 添加至队尾 deque.offerLast(5) deque.offerLast(4) deque.offerFirst(3) // 添加至队首 @@ -293,11 +289,11 @@ deque.offerFirst(1) /* 访问元素 */ val peekFirst = deque.peekFirst() // 队首元素 -val peekLast = deque.peekLast() // 队尾元素 +val peekLast = deque.peekLast() // 队尾元素 /* 元素出队 */ val popFirst = deque.pollFirst() // 队首元素出队 -val popLast = deque.pollLast() // 队尾元素出队 +val popLast = deque.pollLast() // 队尾元素出队 /* 获取双向队列的长度 */ val size = deque.size @@ -308,10 +304,10 @@ val isEmpty = deque.isEmpty() ```ruby title="deque.rb" # 初始化双向队列 -# Ruby 没有内直的双端队列,只能把 Array 当作双端队列来使用 +# Ruby 没有内置的双端队列,只能把 Array 当作双端队列来使用 deque = [] -# 元素如队 +# 元素入队 deque << 2 deque << 5 deque << 4 @@ -324,7 +320,7 @@ peek_first = deque.first peek_last = deque.last # 元素出队 -# 请注意,由于是数组, Array#shift 方法的时间复杂度为 O(n) +# 请注意,由于是数组,Array#shift 方法的时间复杂度为 O(n) pop_front = deque.shift pop_back = deque.pop diff --git a/codes/snippets/chapter_stack_and_queue/queue.md b/codes/snippets/chapter_stack_and_queue/queue.md index 801637e72..48fdf906d 100644 --- a/codes/snippets/chapter_stack_and_queue/queue.md +++ b/codes/snippets/chapter_stack_and_queue/queue.md @@ -141,7 +141,7 @@ queue.append(4) let peek = queue.first! /* 元素出队 */ -// 由于是数组,因此 removeFirst 的复杂度为 O(n) +// 使用 Array 模拟时 removeFirst 的复杂度为 O(n) let pop = queue.removeFirst() /* 获取队列的长度 */ @@ -174,7 +174,7 @@ const pop = queue.shift(); const size = queue.length; /* 判断队列是否为空 */ -const empty = queue.length === 0; +const isEmpty = queue.length === 0; ``` ```typescript title="queue.ts" @@ -200,13 +200,13 @@ const pop = queue.shift(); const size = queue.length; /* 判断队列是否为空 */ -const empty = queue.length === 0; +const isEmpty = queue.length === 0; ``` ```dart title="queue.dart" /* 初始化队列 */ -// 在 Dart 中,队列类 Queue 是双向队列,也可作为队列使用 -Queue queue = Queue(); +// 在 Dart 中,一般将双向队列类 Queue 当作队列使用 +final Queue queue = Queue(); /* 元素入队 */ queue.add(1); @@ -216,43 +216,41 @@ queue.add(5); queue.add(4); /* 访问队首元素 */ -int peek = queue.first; +final int peek = queue.first; /* 元素出队 */ -int pop = queue.removeFirst(); +final int pop = queue.removeFirst(); /* 获取队列的长度 */ -int size = queue.length; +final int size = queue.length; /* 判断队列是否为空 */ -bool isEmpty = queue.isEmpty; +final bool isEmpty = queue.isEmpty; ``` ```rust title="queue.rs" -/* 初始化双向队列 */ -// 在 Rust 中使用双向队列作为普通队列来使用 -let mut deque: VecDeque = VecDeque::new(); +// 初始化队列 +// 在 Rust 中,一般将双向队列 VecDeque 看作队列使用 +let mut queue: VecDeque = VecDeque::new(); -/* 元素入队 */ -deque.push_back(1); -deque.push_back(3); -deque.push_back(2); -deque.push_back(5); -deque.push_back(4); +// 元素入队 +queue.push_back(1); +queue.push_back(3); +queue.push_back(2); +queue.push_back(5); +queue.push_back(4); -/* 访问队首元素 */ -if let Some(front) = deque.front() { -} +// 访问队首元素 +let peek = queue.front().unwrap(); -/* 元素出队 */ -if let Some(pop) = deque.pop_front() { -} +// 元素出队 +let pop = queue.pop_front().unwrap(); -/* 获取队列的长度 */ -let size = deque.len(); +// 获取队列的长度 +let size = queue.len(); -/* 判断队列是否为空 */ -let is_empty = deque.is_empty(); +// 判断队列是否为空 +let is_empty = queue.is_empty(); ``` ```c title="queue.c" @@ -285,7 +283,7 @@ val isEmpty = queue.isEmpty() ```ruby title="queue.rb" # 初始化队列 -# Ruby 内置的队列(Thread::Queue) 没有 peek 和遍历方法,可以把 Array 当作队列来使用 +# Ruby 内置的队列(Thread::Queue)没有 peek 和遍历方法,可以把 Array 当作队列来使用 queue = [] # 元素入队 @@ -299,7 +297,7 @@ queue.push(4) peek = queue.first # 元素出队 -# 清注意,由于是数组,Array#shift 方法时间复杂度为 O(n) +# 请注意,由于是数组,Array#shift 方法的时间复杂度为 O(n) pop = queue.shift # 获取队列的长度 diff --git a/codes/snippets/chapter_stack_and_queue/stack.md b/codes/snippets/chapter_stack_and_queue/stack.md index 31de324a9..1c859f9a2 100644 --- a/codes/snippets/chapter_stack_and_queue/stack.md +++ b/codes/snippets/chapter_stack_and_queue/stack.md @@ -160,7 +160,7 @@ stack.push(5); stack.push(4); /* 访问栈顶元素 */ -const peek = stack[stack.length-1]; +const peek = stack[stack.length - 1]; /* 元素出栈 */ const pop = stack.pop(); @@ -169,7 +169,7 @@ const pop = stack.pop(); const size = stack.length; /* 判断是否为空 */ -const is_empty = stack.length === 0; +const isEmpty = stack.length === 0; ``` ```typescript title="stack.ts" @@ -194,13 +194,13 @@ const pop = stack.pop(); const size = stack.length; /* 判断是否为空 */ -const is_empty = stack.length === 0; +const isEmpty = stack.length === 0; ``` ```dart title="stack.dart" /* 初始化栈 */ // Dart 没有内置的栈类,可以把 List 当作栈来使用 -List stack = []; +final List stack = []; /* 元素入栈 */ stack.add(1); @@ -210,40 +210,40 @@ stack.add(5); stack.add(4); /* 访问栈顶元素 */ -int peek = stack.last; +final int peek = stack.last; /* 元素出栈 */ -int pop = stack.removeLast(); +final int pop = stack.removeLast(); /* 获取栈的长度 */ -int size = stack.length; +final int size = stack.length; /* 判断是否为空 */ -bool isEmpty = stack.isEmpty; +final bool isEmpty = stack.isEmpty; ``` ```rust title="stack.rs" -/* 初始化栈 */ -// 把 Vec 当作栈来使用 +// 初始化栈 +// 在 Rust 中,推荐将 Vec 当作栈来使用 let mut stack: Vec = Vec::new(); -/* 元素入栈 */ +// 元素入栈 stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* 访问栈顶元素 */ -let top = stack.last().unwrap(); +// 访问栈顶元素 +let peek = stack.last().unwrap(); -/* 元素出栈 */ +// 元素出栈 let pop = stack.pop().unwrap(); -/* 获取栈的长度 */ +// 获取栈的长度 let size = stack.len(); -/* 判断是否为空 */ +// 判断栈是否为空 let is_empty = stack.is_empty(); ``` diff --git a/codes/snippets/chapter_tree/binary_tree.md b/codes/snippets/chapter_tree/binary_tree.md index c7cf5fb70..921a98be6 100644 --- a/codes/snippets/chapter_tree/binary_tree.md +++ b/codes/snippets/chapter_tree/binary_tree.md @@ -133,7 +133,6 @@ impl TreeNode { /* 二叉树节点结构体 */ typedef struct TreeNode { int val; // 节点值 - int height; // 节点高度 struct TreeNode *left; // 左子节点指针 struct TreeNode *right; // 右子节点指针 } TreeNode; @@ -144,7 +143,6 @@ TreeNode *newTreeNode(int val) { node = (TreeNode *)malloc(sizeof(TreeNode)); node->val = val; - node->height = 0; node->left = NULL; node->right = NULL; return node; @@ -191,11 +189,11 @@ n2.right = n5 ```cpp title="binary_tree.cpp" /* 初始化二叉树 */ // 初始化节点 -TreeNode* n1 = new TreeNode(1); -TreeNode* n2 = new TreeNode(2); -TreeNode* n3 = new TreeNode(3); -TreeNode* n4 = new TreeNode(4); -TreeNode* n5 = new TreeNode(5); +TreeNode *n1 = new TreeNode(1); +TreeNode *n2 = new TreeNode(2); +TreeNode *n3 = new TreeNode(3); +TreeNode *n4 = new TreeNode(4); +TreeNode *n5 = new TreeNode(5); // 构建节点之间的引用(指针) n1->left = n2; n1->right = n3; @@ -204,6 +202,7 @@ n2->right = n5; ``` ```java title="binary_tree.java" +/* 初始化二叉树 */ // 初始化节点 TreeNode n1 = new TreeNode(1); TreeNode n2 = new TreeNode(2); @@ -248,6 +247,7 @@ n2.Right = n5 ``` ```swift title="binary_tree.swift" +/* 初始化二叉树 */ // 初始化节点 let n1 = TreeNode(x: 1) let n2 = TreeNode(x: 2) @@ -294,11 +294,11 @@ n2.right = n5; ```dart title="binary_tree.dart" /* 初始化二叉树 */ // 初始化节点 -TreeNode n1 = new TreeNode(1); -TreeNode n2 = new TreeNode(2); -TreeNode n3 = new TreeNode(3); -TreeNode n4 = new TreeNode(4); -TreeNode n5 = new TreeNode(5); +TreeNode n1 = TreeNode(1); +TreeNode n2 = TreeNode(2); +TreeNode n3 = TreeNode(3); +TreeNode n4 = TreeNode(4); +TreeNode n5 = TreeNode(5); // 构建节点之间的引用(指针) n1.left = n2; n1.right = n3; @@ -307,6 +307,7 @@ n2.right = n5; ``` ```rust title="binary_tree.rs" +/* 初始化二叉树 */ // 初始化节点 let n1 = TreeNode::new(1); let n2 = TreeNode::new(2); @@ -314,10 +315,10 @@ let n3 = TreeNode::new(3); let n4 = TreeNode::new(4); let n5 = TreeNode::new(5); // 构建节点之间的引用(指针) -n1.borrow_mut().left = Some(n2.clone()); -n1.borrow_mut().right = Some(n3); -n2.borrow_mut().left = Some(n4); -n2.borrow_mut().right = Some(n5); +n1.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().right = Some(Rc::clone(&n3)); +n2.borrow_mut().left = Some(Rc::clone(&n4)); +n2.borrow_mut().right = Some(Rc::clone(&n5)); ``` ```c title="binary_tree.c" @@ -336,6 +337,7 @@ n2->right = n5; ``` ```kotlin title="binary_tree.kt" +/* 初始化二叉树 */ // 初始化节点 val n1 = TreeNode(1) val n2 = TreeNode(2) @@ -370,27 +372,27 @@ https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%2 ```python title="binary_tree.py" # 插入与删除节点 -p = TreeNode(0) +P = TreeNode(0) # 在 n1 -> n2 中间插入节点 P -n1.left = p -p.left = n2 +n1.left = P +P.left = n2 # 删除节点 P n1.left = n2 ``` ```cpp title="binary_tree.cpp" /* 插入与删除节点 */ -TreeNode* P = new TreeNode(0); +TreeNode *P = new TreeNode(0); // 在 n1 -> n2 中间插入节点 P n1->left = P; P->left = n2; // 删除节点 P n1->left = n2; -// 释放内存 -delete P; +delete P; // 释放内存 ``` ```java title="binary_tree.java" +/* 插入与删除节点 */ TreeNode P = new TreeNode(0); // 在 n1 -> n2 中间插入节点 P n1.left = P; @@ -420,6 +422,7 @@ n1.Left = n2 ``` ```swift title="binary_tree.swift" +/* 插入与删除节点 */ let P = TreeNode(x: 0) // 在 n1 -> n2 中间插入节点 P n1.left = P @@ -430,7 +433,7 @@ n1.left = n2 ```javascript title="binary_tree.js" /* 插入与删除节点 */ -let P = new TreeNode(0); +const P = new TreeNode(0); // 在 n1 -> n2 中间插入节点 P n1.left = P; P.left = n2; @@ -450,21 +453,23 @@ n1.left = n2; ```dart title="binary_tree.dart" /* 插入与删除节点 */ -TreeNode P = new TreeNode(0); +TreeNode p = TreeNode(0); // 在 n1 -> n2 中间插入节点 P -n1.left = P; -P.left = n2; +n1.left = p; +p.left = n2; // 删除节点 P n1.left = n2; ``` ```rust title="binary_tree.rs" +/* 插入与删除节点 */ let p = TreeNode::new(0); // 在 n1 -> n2 中间插入节点 P -n1.borrow_mut().left = Some(p.clone()); -p.borrow_mut().left = Some(n2.clone()); -// 删除节点 p -n1.borrow_mut().left = Some(n2); +p.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().left = Some(Rc::clone(&p)); +// 删除节点 P +drop(p); +n1.borrow_mut().left = Some(Rc::clone(&n2)); ``` ```c title="binary_tree.c" @@ -480,6 +485,7 @@ free(P); ``` ```kotlin title="binary_tree.kt" +/* 插入与删除节点 */ val P = TreeNode(0) // 在 n1 -> n2 中间插入节点 P n1.left = P @@ -499,4 +505,4 @@ n1.left = n2 ``` -https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20P%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20P%0A%20%20%20%20P.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/codes/swift/chapter_stack_and_queue/deque.swift b/codes/swift/chapter_stack_and_queue/deque.swift index 8245caf55..2215fbb7c 100644 --- a/codes/swift/chapter_stack_and_queue/deque.swift +++ b/codes/swift/chapter_stack_and_queue/deque.swift @@ -27,7 +27,7 @@ enum Deque { print("队尾元素 peekLast = \(peekLast)") /* 元素出队 */ - // 使用 Array 模拟时 popFirst 的复杂度为 O(n) + // 使用 Array 模拟时 removeFirst 的复杂度为 O(n) let popFirst = deque.removeFirst() print("队首出队元素 popFirst = \(popFirst),队首出队后 deque = \(deque)") let popLast = deque.removeLast() diff --git a/codes/swift/chapter_stack_and_queue/queue.swift b/codes/swift/chapter_stack_and_queue/queue.swift index 84ef7f8fe..218c25fd5 100644 --- a/codes/swift/chapter_stack_and_queue/queue.swift +++ b/codes/swift/chapter_stack_and_queue/queue.swift @@ -25,7 +25,7 @@ enum Queue { print("队首元素 peek = \(peek)") /* 元素出队 */ - // 使用 Array 模拟时 pop 的复杂度为 O(n) + // 使用 Array 模拟时 removeFirst 的复杂度为 O(n) let pop = queue.removeFirst() print("出队元素 pop = \(pop),出队后 queue = \(queue)") diff --git a/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts b/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts index f4ae6ed7c..54777a5a8 100644 --- a/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -6,8 +6,8 @@ /* 双向链表节点 */ class ListNode { - prev: ListNode; // 前驱节点引用 (指针) - next: ListNode; // 后继节点引用 (指针) + prev: ListNode | null; // 前驱节点引用 (指针) + next: ListNode | null; // 后继节点引用 (指针) val: number; // 节点值 constructor(val: number) { diff --git a/en/codes/c/chapter_array_and_linkedlist/array.c b/en/codes/c/chapter_array_and_linkedlist/array.c index a1aabfaf8..a6de9ca31 100644 --- a/en/codes/c/chapter_array_and_linkedlist/array.c +++ b/en/codes/c/chapter_array_and_linkedlist/array.c @@ -75,7 +75,7 @@ int main() { /* Initialize the array */ int size = 5; - int arr[5]; + int arr[5] = {0}; printf("Array arr = "); printArray(arr, size); diff --git a/en/codes/c/chapter_stack_and_queue/array_queue.c b/en/codes/c/chapter_stack_and_queue/array_queue.c index 6f78102d3..828dee363 100644 --- a/en/codes/c/chapter_stack_and_queue/array_queue.c +++ b/en/codes/c/chapter_stack_and_queue/array_queue.c @@ -123,7 +123,7 @@ int main() { for (int i = 0; i < 10; i++) { push(queue, i); pop(queue); - printf("After enqueueing and dequeueing in round %d, queue = ", i); + printf("After round %d of enqueue + dequeue, queue = ", i); printArray(toArray(queue, &queSize), queSize); } diff --git a/en/codes/c/utils/list_node.h b/en/codes/c/utils/list_node.h index 58040602c..5de7a2327 100644 --- a/en/codes/c/utils/list_node.h +++ b/en/codes/c/utils/list_node.h @@ -14,7 +14,7 @@ extern "C" { /* Linked list node structure */ typedef struct ListNode { int val; // Node value - struct ListNode *next; // Reference to the next node + struct ListNode *next; // Pointer to the next node } ListNode; /* Constructor: initialize a new node */ diff --git a/en/codes/cpp/chapter_array_and_linkedlist/array.cpp b/en/codes/cpp/chapter_array_and_linkedlist/array.cpp index 2148e6586..4a55ef893 100644 --- a/en/codes/cpp/chapter_array_and_linkedlist/array.cpp +++ b/en/codes/cpp/chapter_array_and_linkedlist/array.cpp @@ -18,7 +18,7 @@ int randomAccess(int *nums, int size) { /* Extend the array length */ int *extend(int *nums, int size, int enlarge) { // Initialize an array with the extended length - int *res = new int[size + enlarge]; + int *res = new int[size + enlarge]{}; // Copy all elements from the original array to the new array for (int i = 0; i < size; i++) { res[i] = nums[i]; @@ -69,7 +69,7 @@ int find(int *nums, int size, int target) { int main() { /* Initialize the array */ int size = 5; - int *arr = new int[size]; + int *arr = new int[size]{}; cout << "Array arr = "; printArray(arr, size); diff --git a/en/codes/cpp/chapter_array_and_linkedlist/linked_list.cpp b/en/codes/cpp/chapter_array_and_linkedlist/linked_list.cpp index 1e0f73a7d..26e881984 100644 --- a/en/codes/cpp/chapter_array_and_linkedlist/linked_list.cpp +++ b/en/codes/cpp/chapter_array_and_linkedlist/linked_list.cpp @@ -76,7 +76,7 @@ int main() { /* Access a node */ ListNode *node = access(n0, 3); - cout << "Value of the linked list node at index 3 = " << node->val << endl; + cout << "Value of the node at index 3 in the linked list = " << node->val << endl; /* Find a node */ int index = find(n0, 2); diff --git a/en/codes/cpp/chapter_hashing/built_in_hash.cpp b/en/codes/cpp/chapter_hashing/built_in_hash.cpp index 08a605ecf..276ad4de0 100644 --- a/en/codes/cpp/chapter_hashing/built_in_hash.cpp +++ b/en/codes/cpp/chapter_hashing/built_in_hash.cpp @@ -24,6 +24,6 @@ int main() { size_t hashStr = hash()(str); cout << "String " << str << " has hash value " << hashStr << "\n"; - // C++ std::hash provides hashing for fundamental types and selected standard-library types - // For arrays and unsupported object types, supply your own hash implementation + // In C++, the built-in std::hash() only computes hash values for basic data types + // Hashing arrays and objects requires a custom implementation } diff --git a/en/codes/cpp/chapter_stack_and_queue/array_queue.cpp b/en/codes/cpp/chapter_stack_and_queue/array_queue.cpp index 3cadb4f08..657b8b876 100644 --- a/en/codes/cpp/chapter_stack_and_queue/array_queue.cpp +++ b/en/codes/cpp/chapter_stack_and_queue/array_queue.cpp @@ -118,7 +118,7 @@ int main() { for (int i = 0; i < 10; i++) { queue->push(i); queue->pop(); - cout << "Round " << i << " : after enqueue + dequeue, queue = "; + cout << "After round " << i << " of enqueue + dequeue, queue = "; printVector(queue->toVector()); } diff --git a/en/codes/csharp/chapter_stack_and_queue/array_queue.cs b/en/codes/csharp/chapter_stack_and_queue/array_queue.cs index 8bfc07143..1001d02c1 100644 --- a/en/codes/csharp/chapter_stack_and_queue/array_queue.cs +++ b/en/codes/csharp/chapter_stack_and_queue/array_queue.cs @@ -108,7 +108,7 @@ public class array_queue { for (int i = 0; i < 10; i++) { queue.Push(i); queue.Pop(); - Console.WriteLine("Round " + i + " : after enqueue + dequeue, queue = " + string.Join(",", queue.ToArray())); + Console.WriteLine("After round " + i + " of enqueue + dequeue, queue = " + string.Join(",", queue.ToArray())); } } } diff --git a/en/codes/dart/chapter_hashing/built_in_hash.dart b/en/codes/dart/chapter_hashing/built_in_hash.dart index 42fc209f0..9939c8a63 100644 --- a/en/codes/dart/chapter_hashing/built_in_hash.dart +++ b/en/codes/dart/chapter_hashing/built_in_hash.dart @@ -18,7 +18,7 @@ void main() { double dec = 3.14159; int hashDec = dec.hashCode; - print("Hash value of decimal $dec: $hashDec"); + print("Floating-point number $dec has hash value $hashDec"); String str = "Hello 算法"; int hashStr = str.hashCode; @@ -26,9 +26,9 @@ void main() { List arr = [12836, "小哈"]; int hashArr = arr.hashCode; - print("Hash value of array $arr: $hashArr"); + print("Array $arr has hash value $hashArr"); ListNode obj = new ListNode(0); int hashObj = obj.hashCode; - print("Hash value of node object $obj: $hashObj"); + print("Node object $obj has hash value $hashObj"); } diff --git a/en/codes/dart/chapter_hashing/hash_map.dart b/en/codes/dart/chapter_hashing/hash_map.dart index 93dd19d74..d7d49a4c2 100644 --- a/en/codes/dart/chapter_hashing/hash_map.dart +++ b/en/codes/dart/chapter_hashing/hash_map.dart @@ -36,6 +36,5 @@ void main() { print("\nTraverse keys only: Key"); map.keys.forEach((key) => print(key)); print("\nTraverse values only: Value"); - map.forEach((key, value) => print("$value")); map.values.forEach((value) => print(value)); } diff --git a/en/codes/dart/chapter_stack_and_queue/array_queue.dart b/en/codes/dart/chapter_stack_and_queue/array_queue.dart index f51cbc085..8d8e7451f 100644 --- a/en/codes/dart/chapter_stack_and_queue/array_queue.dart +++ b/en/codes/dart/chapter_stack_and_queue/array_queue.dart @@ -105,6 +105,6 @@ void main() { for (int i = 0; i < 10; i++) { queue.push(i); queue.pop(); - print("Round $i: after enqueue + dequeue, queue = ${queue.toArray()}"); + print("After round $i of enqueue + dequeue, queue = ${queue.toArray()}"); } } diff --git a/en/codes/dart/chapter_tree/binary_tree.dart b/en/codes/dart/chapter_tree/binary_tree.dart index 6717fdabe..db3d39983 100644 --- a/en/codes/dart/chapter_tree/binary_tree.dart +++ b/en/codes/dart/chapter_tree/binary_tree.dart @@ -28,10 +28,10 @@ void main() { // Insert node p between n1 and n2 n1.left = p; p.left = n2; - print("\nAfter inserting node p:\n"); + print("\nAfter inserting node P:\n"); printTree(n1); - // Remove node p + // Remove node P n1.left = n2; - print("\nAfter removing node p:\n"); + print("\nAfter removing node P:\n"); printTree(n1); } diff --git a/en/codes/go/chapter_array_and_linkedlist/linked_list_test.go b/en/codes/go/chapter_array_and_linkedlist/linked_list_test.go index 4f2a2d3a2..b5938f96d 100644 --- a/en/codes/go/chapter_array_and_linkedlist/linked_list_test.go +++ b/en/codes/go/chapter_array_and_linkedlist/linked_list_test.go @@ -40,7 +40,7 @@ func TestLinkedList(t *testing.T) { /* Access a node */ node := access(n0, 3) - fmt.Println("Node at index 3 in the linked list =", node) + fmt.Println("Value of the node at index 3 in the linked list =", node) /* Find a node */ index := findNode(n0, 2) diff --git a/en/codes/go/chapter_heap/heap.go b/en/codes/go/chapter_heap/heap.go index 9d99bc57c..6e26efcb4 100644 --- a/en/codes/go/chapter_heap/heap.go +++ b/en/codes/go/chapter_heap/heap.go @@ -8,14 +8,14 @@ package chapter_heap // Implementing heap.Interface also requires implementing sort.Interface type intHeap []any -// Push implements heap.Interface by appending an element for the heap package +// Push is a heap.Interface function that pushes an element onto the heap func (h *intHeap) Push(x any) { // Push and Pop use pointer receivers // because they modify the slice length as well as its contents. *h = append(*h, x.(int)) } -// Pop implements heap.Interface by removing the last element, where heap.Pop has moved the top element +// Pop is a heap.Interface function that pops the top element from the heap func (h *intHeap) Pop() any { // The element to remove is stored at the end last := (*h)[len(*h)-1] diff --git a/en/codes/go/chapter_heap/heap_test.go b/en/codes/go/chapter_heap/heap_test.go index 07e98634b..c2ace8353 100644 --- a/en/codes/go/chapter_heap/heap_test.go +++ b/en/codes/go/chapter_heap/heap_test.go @@ -14,14 +14,14 @@ import ( ) func testPush(h *intHeap, val int) { - // Call heap.Push, which uses heap.Interface to add an element + // Call a heap.Interface function to add an element heap.Push(h, val) fmt.Printf("\nAfter pushing %d onto the heap: \n", val) PrintHeap(*h) } func testPop(h *intHeap) { - // Call heap.Pop, which uses heap.Interface to remove the top element + // Call a heap.Interface function to remove an element val := heap.Pop(h) fmt.Printf("\nAfter popping the top element %d from the heap: \n", val) PrintHeap(*h) @@ -91,8 +91,6 @@ func TestMyHeap(t *testing.T) { } func TestTopKHeap(t *testing.T) { - /* Initialize the heap */ - // Prepare the input for heap-based top-k selection nums := []int{1, 7, 6, 3, 2} k := 3 res := topKHeap(nums, k) diff --git a/en/codes/go/chapter_stack_and_queue/deque_test.go b/en/codes/go/chapter_stack_and_queue/deque_test.go index 354f4f76f..b62cce555 100644 --- a/en/codes/go/chapter_stack_and_queue/deque_test.go +++ b/en/codes/go/chapter_stack_and_queue/deque_test.go @@ -51,7 +51,6 @@ func TestDeque(t *testing.T) { func TestArrayDeque(t *testing.T) { /* Initialize the deque */ - // Use the custom circular-array deque implementation deque := newArrayDeque(16) /* Enqueue elements */ diff --git a/en/codes/go/chapter_stack_and_queue/queue_test.go b/en/codes/go/chapter_stack_and_queue/queue_test.go index 7a5fdf6d9..9c9b568db 100644 --- a/en/codes/go/chapter_stack_and_queue/queue_test.go +++ b/en/codes/go/chapter_stack_and_queue/queue_test.go @@ -47,7 +47,7 @@ func TestQueue(t *testing.T) { func TestArrayQueue(t *testing.T) { - // Initialize the queue and use its standard queue operations + // Initialize the queue and use the common queue interface capacity := 10 queue := newArrayQueue(capacity) if queue.pop() != nil { @@ -84,7 +84,7 @@ func TestArrayQueue(t *testing.T) { for i := 0; i < 10; i++ { queue.push(i) queue.pop() - fmt.Print("Round #", i, ": after enqueue + dequeue, queue =") + fmt.Print("After round ", i, " of enqueue + dequeue, queue =") PrintSlice(queue.toSlice()) } } diff --git a/en/codes/go/chapter_stack_and_queue/stack_test.go b/en/codes/go/chapter_stack_and_queue/stack_test.go index 36dc1856d..ecb49bd78 100644 --- a/en/codes/go/chapter_stack_and_queue/stack_test.go +++ b/en/codes/go/chapter_stack_and_queue/stack_test.go @@ -45,7 +45,7 @@ func TestStack(t *testing.T) { } func TestArrayStack(t *testing.T) { - // Initialize the stack for use through its stack operations + // Initialize the stack and assign it to an interface stack := newArrayStack() // Push elements onto the stack diff --git a/en/codes/go/chapter_tree/binary_tree_test.go b/en/codes/go/chapter_tree/binary_tree_test.go index 17f0ca53a..f98f161e7 100644 --- a/en/codes/go/chapter_tree/binary_tree_test.go +++ b/en/codes/go/chapter_tree/binary_tree_test.go @@ -32,10 +32,10 @@ func TestBinaryTree(t *testing.T) { p := NewTreeNode(0) n1.Left = p p.Left = n2 - fmt.Println("After inserting node p") + fmt.Println("After inserting node P") PrintTree(n1) // Remove a node n1.Left = n2 - fmt.Println("After removing node p") + fmt.Println("After removing node P") PrintTree(n1) } diff --git a/en/codes/java/chapter_array_and_linkedlist/list.java b/en/codes/java/chapter_array_and_linkedlist/list.java index 5499f0d48..7daac1d2b 100644 --- a/en/codes/java/chapter_array_and_linkedlist/list.java +++ b/en/codes/java/chapter_array_and_linkedlist/list.java @@ -11,7 +11,7 @@ import java.util.*; public class list { public static void main(String[] args) { /* Initialize the list */ - // Use Integer[]: Integer is the wrapper type for int + // Note that the array type must be Integer[] rather than int[], because list elements must use Integer, the wrapper class for int Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); System.out.println("List nums = " + nums); diff --git a/en/codes/java/chapter_hashing/built_in_hash.java b/en/codes/java/chapter_hashing/built_in_hash.java index 9ac1470bd..1a45f39e5 100644 --- a/en/codes/java/chapter_hashing/built_in_hash.java +++ b/en/codes/java/chapter_hashing/built_in_hash.java @@ -21,7 +21,7 @@ public class built_in_hash { double dec = 3.14159; int hashDec = Double.hashCode(dec); - System.out.println("Decimal " + dec + " has hash value " + hashDec); + System.out.println("Floating-point number " + dec + " has hash value " + hashDec); String str = "Hello 算法"; int hashStr = str.hashCode(); diff --git a/en/codes/java/chapter_stack_and_queue/array_queue.java b/en/codes/java/chapter_stack_and_queue/array_queue.java index 662e957b7..83e58b4e4 100644 --- a/en/codes/java/chapter_stack_and_queue/array_queue.java +++ b/en/codes/java/chapter_stack_and_queue/array_queue.java @@ -109,7 +109,7 @@ public class array_queue { for (int i = 0; i < 10; i++) { queue.push(i); queue.pop(); - System.out.println("Round " + i + " : after enqueue + dequeue, queue = " + Arrays.toString(queue.toArray())); + System.out.println("After round " + i + " of enqueue + dequeue, queue = " + Arrays.toString(queue.toArray())); } } } diff --git a/en/codes/javascript/chapter_stack_and_queue/array_queue.js b/en/codes/javascript/chapter_stack_and_queue/array_queue.js index ab158c4fb..b454ddf6c 100644 --- a/en/codes/javascript/chapter_stack_and_queue/array_queue.js +++ b/en/codes/javascript/chapter_stack_and_queue/array_queue.js @@ -102,5 +102,5 @@ console.log('Is the queue empty = ' + isEmpty); for (let i = 0; i < 10; i++) { queue.push(i); queue.pop(); - console.log('Round ' + i + ' : after enqueue + dequeue, queue =', queue.toArray()); + console.log('After round ' + i + ' of enqueue + dequeue, queue =', queue.toArray()); } diff --git a/en/codes/kotlin/chapter_array_and_linkedlist/linked_list.kt b/en/codes/kotlin/chapter_array_and_linkedlist/linked_list.kt index 76b987b41..5829400c6 100644 --- a/en/codes/kotlin/chapter_array_and_linkedlist/linked_list.kt +++ b/en/codes/kotlin/chapter_array_and_linkedlist/linked_list.kt @@ -9,7 +9,7 @@ package chapter_array_and_linkedlist import utils.ListNode import utils.printLinkedList -/* Insert node p after node n0 in the linked list */ +/* Insert node P after node n0 in the linked list */ fun insert(n0: ListNode?, p: ListNode?) { val n1 = n0?.next p?.next = n1 diff --git a/en/codes/kotlin/chapter_stack_and_queue/array_queue.kt b/en/codes/kotlin/chapter_stack_and_queue/array_queue.kt index 444b781cd..3bfe89177 100644 --- a/en/codes/kotlin/chapter_stack_and_queue/array_queue.kt +++ b/en/codes/kotlin/chapter_stack_and_queue/array_queue.kt @@ -105,6 +105,6 @@ fun main() { for (i in 0..9) { queue.push(i) queue.pop() - println("After enqueue and dequeue round $i: queue = ${queue.toArray().contentToString()}") + println("After round $i of enqueue + dequeue, queue = ${queue.toArray().contentToString()}") } } \ No newline at end of file diff --git a/en/codes/python/chapter_hashing/built_in_hash.py b/en/codes/python/chapter_hashing/built_in_hash.py index b5534c861..6c3b0bf6f 100644 --- a/en/codes/python/chapter_hashing/built_in_hash.py +++ b/en/codes/python/chapter_hashing/built_in_hash.py @@ -14,15 +14,15 @@ from modules import ListNode if __name__ == "__main__": num = 3 hash_num = hash(num) - print(f"Hash value of integer {num}: {hash_num}") + print(f"Integer {num} has hash value {hash_num}") bol = True hash_bol = hash(bol) - print(f"Hash value of Boolean {bol}: {hash_bol}") + print(f"Boolean {bol} has hash value {hash_bol}") dec = 3.14159 hash_dec = hash(dec) - print(f"Hash value of floating-point number {dec}: {hash_dec}") + print(f"Floating-point number {dec} has hash value {hash_dec}") str = "Hello 算法" hash_str = hash(str) @@ -30,8 +30,8 @@ if __name__ == "__main__": tup = (12836, "小哈") hash_tup = hash(tup) - print(f"Hash of the hash value of tuple {tup}: {hash(hash_tup)}") + print(f"Tuple {tup} has hash value {hash_tup}") obj = ListNode(0) hash_obj = hash(obj) - print(f"Hash value of node object {obj}: {hash_obj}") + print(f"Node object {obj} has hash value {hash_obj}") diff --git a/en/codes/python/chapter_stack_and_queue/array_queue.py b/en/codes/python/chapter_stack_and_queue/array_queue.py index 3feb3583c..c3eca8f47 100644 --- a/en/codes/python/chapter_stack_and_queue/array_queue.py +++ b/en/codes/python/chapter_stack_and_queue/array_queue.py @@ -95,4 +95,4 @@ if __name__ == "__main__": for i in range(10): queue.push(i) queue.pop() - print("Round", i, ": after enqueue + dequeue, queue = ", queue.to_list()) + print("After round", i, "of enqueue + dequeue, queue = ", queue.to_list()) diff --git a/en/codes/python/chapter_stack_and_queue/deque.py b/en/codes/python/chapter_stack_and_queue/deque.py index af4e203cf..a5decd771 100644 --- a/en/codes/python/chapter_stack_and_queue/deque.py +++ b/en/codes/python/chapter_stack_and_queue/deque.py @@ -17,7 +17,7 @@ if __name__ == "__main__": deq.append(4) deq.appendleft(3) # Add to the front deq.appendleft(1) - print("Deque deq =", deq) + print("Deque deque =", deq) # Access an element front: int = deq[0] # Front element @@ -28,10 +28,10 @@ if __name__ == "__main__": # Dequeue an element pop_front: int = deq.popleft() # Dequeue the front element print("Element dequeued from the front, pop_front =", pop_front) - print("After dequeuing from the front, deq =", deq) + print("After dequeuing from the front, deque =", deq) pop_rear: int = deq.pop() # Dequeue the rear element print("Element dequeued from the rear, pop_rear =", pop_rear) - print("After dequeuing from the rear, deq =", deq) + print("After dequeuing from the rear, deque =", deq) # Get the deque size size: int = len(deq) diff --git a/en/codes/ruby/chapter_hashing/built_in_hash.rb b/en/codes/ruby/chapter_hashing/built_in_hash.rb index 097807841..627106abb 100644 --- a/en/codes/ruby/chapter_hashing/built_in_hash.rb +++ b/en/codes/ruby/chapter_hashing/built_in_hash.rb @@ -10,25 +10,25 @@ require_relative '../utils/list_node' if __FILE__ == $0 num = 3 hash_num = num.hash - puts "Hash value of integer #{num}: #{hash_num}" + puts "Integer #{num} has hash value #{hash_num}" bol = true hash_bol = bol.hash - puts "Hash value of Boolean #{bol}: #{hash_bol}" + puts "Boolean #{bol} has hash value #{hash_bol}" dec = 3.14159 hash_dec = dec.hash - puts "Hash value of floating-point number #{dec}: #{hash_dec}" + puts "Floating-point number #{dec} has hash value #{hash_dec}" str = "Hello 算法" hash_str = str.hash puts "Hash value of string #{str}: #{hash_str}" - tup = [12836, '小哈'] - hash_tup = tup.hash - puts "Hash value of array #{tup}: #{hash_tup}" + arr = [12836, '小哈'] + hash_arr = arr.hash + puts "Array #{arr} has hash value #{hash_arr}" obj = ListNode.new(0) hash_obj = obj.hash - puts "Hash value of node object #{obj}: #{hash_obj}" + puts "Node object #{obj} has hash value #{hash_obj}" end diff --git a/en/codes/ruby/chapter_stack_and_queue/array_queue.rb b/en/codes/ruby/chapter_stack_and_queue/array_queue.rb index 19f46b428..680db994d 100644 --- a/en/codes/ruby/chapter_stack_and_queue/array_queue.rb +++ b/en/codes/ruby/chapter_stack_and_queue/array_queue.rb @@ -102,6 +102,6 @@ if __FILE__ == $0 for i in 0...10 queue.push(i) queue.pop - puts "After enqueueing and dequeueing in round #{i}, queue = #{queue.to_array}" + puts "After round #{i} of enqueue + dequeue, queue = #{queue.to_array}" end end diff --git a/en/codes/ruby/chapter_stack_and_queue/deque.rb b/en/codes/ruby/chapter_stack_and_queue/deque.rb index cf99ca232..71101ed2a 100644 --- a/en/codes/ruby/chapter_stack_and_queue/deque.rb +++ b/en/codes/ruby/chapter_stack_and_queue/deque.rb @@ -14,7 +14,7 @@ if __FILE__ == $0 deque << 2 deque << 5 deque << 4 - # Front insertion in a simple array takes O(n); Ruby implementations can optimize Array#unshift + # Note that Array#unshift has O(n) time complexity because the underlying structure is an array deque.unshift(3) deque.unshift(1) puts "Deque deque = #{deque}" @@ -26,7 +26,7 @@ if __FILE__ == $0 puts "Rear element peek_last = #{peek_last}" # Dequeue an element - # Front removal in a simple array takes O(n); Ruby implementations can optimize Array#shift + # Note that Array#shift has O(n) time complexity because the underlying structure is an array pop_front = deque.shift puts "Element dequeued from the front: pop_front = #{pop_front}; deque = #{deque}" pop_back = deque.pop diff --git a/en/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb b/en/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb index 9e9e15c5c..e9dd0a112 100644 --- a/en/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/en/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,7 +4,7 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end -### Doubly linked list node +### Doubly linked list node ### class ListNode attr_accessor :val attr_accessor :next # Reference to the next node diff --git a/en/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb b/en/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb index 372b1c2e7..ea07e1c26 100644 --- a/en/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb +++ b/en/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb @@ -84,11 +84,11 @@ if __FILE__ == $0 # Access the front element peek = queue.peek - puts "Front element peek = #{peek}" + puts "Front element front = #{peek}" # Dequeue an element pop_front = queue.pop - puts "Dequeued element pop_front = #{pop_front}" + puts "Dequeued element pop = #{pop_front}" puts "After dequeueing, queue = #{queue.to_array}" # Get the queue size diff --git a/en/codes/ruby/chapter_stack_and_queue/queue.rb b/en/codes/ruby/chapter_stack_and_queue/queue.rb index fe0366804..f2b2cb789 100644 --- a/en/codes/ruby/chapter_stack_and_queue/queue.rb +++ b/en/codes/ruby/chapter_stack_and_queue/queue.rb @@ -23,7 +23,7 @@ if __FILE__ == $0 puts "Front element peek = #{peek}" # Dequeue an element - # Front removal in a simple array takes O(n); Ruby implementations can optimize Array#shift + # Note that Array#shift has O(n) time complexity because the underlying structure is an array pop = queue.shift puts "Dequeued element pop = #{pop}" puts "After dequeueing, queue = #{queue}" diff --git a/en/codes/rust/chapter_hashing/build_in_hash.rs b/en/codes/rust/chapter_hashing/build_in_hash.rs index 24c84e1ec..2f688465b 100644 --- a/en/codes/rust/chapter_hashing/build_in_hash.rs +++ b/en/codes/rust/chapter_hashing/build_in_hash.rs @@ -15,19 +15,19 @@ fn main() { let mut num_hasher = DefaultHasher::new(); num.hash(&mut num_hasher); let hash_num = num_hasher.finish(); - println!("Hash of integer {}: {}", num, hash_num); + println!("Integer {} has hash value {}", num, hash_num); let bol = true; let mut bol_hasher = DefaultHasher::new(); bol.hash(&mut bol_hasher); let hash_bol = bol_hasher.finish(); - println!("Hash of boolean {}: {}", bol, hash_bol); + println!("Boolean {} has hash value {}", bol, hash_bol); let dec: f32 = 3.14159; let mut dec_hasher = DefaultHasher::new(); dec.to_bits().hash(&mut dec_hasher); let hash_dec = dec_hasher.finish(); - println!("Hash of the bit representation of floating-point value {}: {}", dec, hash_dec); + println!("Floating-point number {} has hash value {}", dec, hash_dec); let str = "Hello 算法"; let mut str_hasher = DefaultHasher::new(); @@ -39,11 +39,11 @@ fn main() { let mut tup_hasher = DefaultHasher::new(); arr.hash(&mut tup_hasher); let hash_tup = tup_hasher.finish(); - println!("Hash of tuple {:?}: {}", arr, hash_tup); + println!("Tuple {:?} has hash value {}", arr, hash_tup); let node = ListNode::new(42); let mut hasher = DefaultHasher::new(); node.borrow().val.hash(&mut hasher); let hash = hasher.finish(); - println!("Hash of the value in node {:?}: {}", node, hash); + println!("Node object {:?} has hash value {}", node, hash); } diff --git a/en/codes/rust/chapter_stack_and_queue/array_queue.rs b/en/codes/rust/chapter_stack_and_queue/array_queue.rs index 8ee72b1a0..73cc831ff 100644 --- a/en/codes/rust/chapter_stack_and_queue/array_queue.rs +++ b/en/codes/rust/chapter_stack_and_queue/array_queue.rs @@ -120,6 +120,6 @@ fn main() { for i in 0..10 { queue.push(i); queue.pop(); - println!("After enqueueing and dequeueing in round {:?}, queue = {:?}", i, queue.to_vector()); + println!("After round {:?} of enqueue + dequeue, queue = {:?}", i, queue.to_vector()); } } diff --git a/en/codes/rust/chapter_stack_and_queue/deque.rs b/en/codes/rust/chapter_stack_and_queue/deque.rs index 4e80571f4..68a5cfe1a 100644 --- a/en/codes/rust/chapter_stack_and_queue/deque.rs +++ b/en/codes/rust/chapter_stack_and_queue/deque.rs @@ -19,9 +19,9 @@ pub fn main() { // Access an element let peek_first = deque.front().unwrap(); - print!("\nFront element peek_first = {peek_first}"); + print!("\nFront element peekFirst = {peek_first}"); let peek_last = deque.back().unwrap(); - print!("\nRear element peek_last = {peek_last}"); + print!("\nRear element peekLast = {peek_last}"); /* Enqueue elements */ deque.push_back(4); diff --git a/en/codes/rust/chapter_tree/binary_tree.rs b/en/codes/rust/chapter_tree/binary_tree.rs index 4e630bab7..145c772f9 100644 --- a/en/codes/rust/chapter_tree/binary_tree.rs +++ b/en/codes/rust/chapter_tree/binary_tree.rs @@ -25,14 +25,14 @@ fn main() { // Insert and remove nodes let p = TreeNode::new(0); - // Insert node p between n1 and n2 in n1 -> n2 + // Insert node P between n1 and n2 in n1 -> n2 p.borrow_mut().left = Some(Rc::clone(&n2)); n1.borrow_mut().left = Some(Rc::clone(&p)); - println!("\nAfter inserting node p:\n"); + println!("\nAfter inserting node P:\n"); print_util::print_tree(&n1); - // Remove node p + // Remove node P drop(p); n1.borrow_mut().left = Some(Rc::clone(&n2)); - println!("\nAfter removing node p:\n"); + println!("\nAfter removing node P:\n"); print_util::print_tree(&n1); } diff --git a/en/codes/snippets/chapter_array_and_linkedlist/array.md b/en/codes/snippets/chapter_array_and_linkedlist/array.md index 2ea652fe9..97e06bbac 100644 --- a/en/codes/snippets/chapter_array_and_linkedlist/array.md +++ b/en/codes/snippets/chapter_array_and_linkedlist/array.md @@ -1,90 +1,89 @@ ```python title="array.py" -# Initialize arrays +# Initialize the array arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] nums: list[int] = [1, 3, 2, 5, 4] ``` ```cpp title="array.cpp" -/* Initialize arrays */ +/* Initialize the array */ // Stored on the stack int arr[5] = {}; -int nums[5] = { 1, 3, 2, 5, 4 }; +int nums[5] = {1, 3, 2, 5, 4}; // Stored on the heap (memory must be freed manually) -int* arr1 = new int[5] {}; -int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +int *arr1 = new int[5]{}; +int *nums1 = new int[5]{1, 3, 2, 5, 4}; ``` ```java title="array.java" -/* Initialize arrays */ +/* Initialize the array */ int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } int[] nums = { 1, 3, 2, 5, 4 }; ``` ```csharp title="array.cs" -/* Initialize arrays */ +// Initialize the array int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] int[] nums = [1, 3, 2, 5, 4]; ``` ```go title="array.go" -/* Initialize arrays */ +/* Initialize the array */ var arr [5]int -// In Go, [5]int is an array with a specified length; []int is a slice -// Go array lengths are determined at compile time and must be constants -// To make extend() easier to implement, we treat slices as arrays below +// In Go, a type with a specified length ([5]int) is an array; without a length ([]int), it is a slice +// Go array lengths are determined at compile time, so the length must be a constant +// To make the extend() function easier to implement, we treat slices as arrays below nums := []int{1, 3, 2, 5, 4} ``` ```swift title="array.swift" -/* Initialize arrays */ +/* Initialize the array */ let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] -let nums = [1, 3, 2, 5, 4] +var nums = [1, 3, 2, 5, 4] ``` ```javascript title="array.js" -/* Initialize arrays */ -var arr = new Array(5).fill(0); -var nums = [1, 3, 2, 5, 4]; +/* Initialize the array */ +const arr = new Array(5).fill(0); +let nums = [1, 3, 2, 5, 4]; ``` ```typescript title="array.ts" -/* Initialize arrays */ -let arr: number[] = new Array(5).fill(0); +/* Initialize the array */ +const arr: number[] = new Array(5).fill(0); let nums: number[] = [1, 3, 2, 5, 4]; ``` ```dart title="array.dart" -/* Initialize arrays */ -List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +/* Initialize the array */ +var arr = List.filled(5, 0); // [0, 0, 0, 0, 0] List nums = [1, 3, 2, 5, 4]; ``` ```rust title="array.rs" -/* Initialize arrays */ +/* Initialize the array */ let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] -let slice: &[i32] = &[0; 5]; -// In Rust, [i32; 5] is an array with a specified length; &[i32] is a slice -// Rust array lengths are determined at compile time and must be constants -// Vector is Rust's usual dynamic array type -// To make extend() easier to implement, we treat a vector as an array below +// In Rust, [i32; 5] is an array type with a fixed length, whereas &[i32] is a reference to a slice +// Rust array lengths are determined at compile time, so their lengths must be constant expressions +// Vec is the type normally used for dynamic arrays in Rust +// To simplify the extend() method, the following examples use a vector to represent an array let nums: Vec = vec![1, 3, 2, 5, 4]; ``` ```c title="array.c" -/* Initialize arrays */ -int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } -int nums[5] = { 1, 3, 2, 5, 4 }; +/* Initialize the array */ +int arr[5] = {0}; // { 0, 0, 0, 0, 0 } +int nums[] = {1, 3, 2, 5, 4}; ``` ```kotlin title="array.kt" -/* Initialize arrays */ -var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +/* Initialize the array */ +val arr = IntArray(5) // { 0, 0, 0, 0, 0 } var nums = intArrayOf(1, 3, 2, 5, 4) ``` ```ruby title="array.rb" -# Initialize arrays +# Initialize the array arr = Array.new(5, 0) nums = [1, 3, 2, 5, 4] ``` diff --git a/en/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/en/codes/snippets/chapter_array_and_linkedlist/linked_list.md index 8e102c03f..72f243864 100644 --- a/en/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/en/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -2,48 +2,53 @@ ```python title="" class ListNode: """Linked list node class""" + def __init__(self, val: int): - self.val: int = val # Node value - self.next: ListNode | None = None # Reference to the next node + self.val: int = val # Node value + self.next: ListNode | None = None # Reference to the next node ``` ```cpp title="" -/* Linked list node structure */ +/* Linked list node */ struct ListNode { - int val; // Node value - ListNode *next; // Pointer to the next node - ListNode(int x) : val(x), next(nullptr) {} // Constructor + int val; // Node value + ListNode *next; // Pointer to the next node + ListNode(int x) : val(x), next(nullptr) { + } }; ``` ```java title="" -/* Linked list node class */ -class ListNode { - int val; // Node value - ListNode next; // Reference to the next node - ListNode(int x) { val = x; } // Constructor +/* Linked list node */ +public class ListNode { + public int val; // Node value + public ListNode next; // Reference to the next node + + public ListNode(int x) { + val = x; + } } ``` ```csharp title="" -/* Linked list node class */ -class ListNode(int x) { // Constructor - public int val = x; // Node value - public ListNode? next; // Reference to the next node +/* Linked list node */ +public class ListNode(int x) { + public int val = x; // Node value + public ListNode? next; // Reference to the next node } ``` ```go title="" -/* Linked list node structure */ +// ListNode represents a linked list node. type ListNode struct { Val int // Node value Next *ListNode // Pointer to the next node } -// NewListNode constructor: create a new linked list -func NewListNode(val int) *ListNode { +// NewListNode constructs a linked list node. +func NewListNode(v int) *ListNode { return &ListNode{ - Val: val, + Val: v, Next: nil, } } @@ -62,44 +67,54 @@ class ListNode { ``` ```javascript title="" -/* Linked list node class */ +/* Linked list node */ class ListNode { + val; // Node value + next; // Reference (pointer) to the next node constructor(val, next) { - this.val = (val === undefined ? 0 : val); // Node value - this.next = (next === undefined ? null : next); // Reference to the next node + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```typescript title="" -/* Linked list node class */ +/* Linked list node */ class ListNode { - val: number; - next: ListNode | null; + val: number; // Node value + next: ListNode | null; // Reference to the next node constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // Node value - this.next = next === undefined ? null : next; // Reference to the next node + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```dart title="" -/* Linked list node class */ +/* Linked list node */ class ListNode { int val; // Node value ListNode? next; // Reference to the next node + ListNode(this.val, [this.next]); // Constructor } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; -/* Linked list node class */ +use std::rc::Rc; + +/* Linked list node */ #[derive(Debug)] -struct ListNode { - val: i32, // Node value - next: Option>>, // Pointer to the next node +pub struct ListNode { + pub val: T, // Node value + pub next: Option>>>, // Pointer to the next node +} + +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None })) + } } ``` @@ -110,10 +125,10 @@ typedef struct ListNode { struct ListNode *next; // Pointer to the next node } ListNode; -/* Constructor */ +/* Constructor: initialize a new node */ ListNode *newListNode(int val) { ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); + node = (ListNode *)malloc(sizeof(ListNode)); node->val = val; node->next = NULL; return node; @@ -121,16 +136,14 @@ ListNode *newListNode(int val) { ``` ```kotlin title="" -/* Linked list node class */ -// Constructor -class ListNode(x: Int) { - val _val: Int = x // Node value +/* Linked list node */ +class ListNode(var _val: Int) { var next: ListNode? = null // Reference to the next node } ``` ```ruby title="" -# Linked list node class +### Linked list node class ### class ListNode attr_accessor :val # Node value attr_accessor :next # Reference to the next node @@ -145,13 +158,13 @@ end ```python title="linked_list.py" # Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 -# Initialize the nodes +# Initialize the individual nodes n0 = ListNode(1) n1 = ListNode(3) n2 = ListNode(2) n3 = ListNode(5) n4 = ListNode(4) -# Link the nodes with references +# Set up references between the nodes n0.next = n1 n1.next = n2 n2.next = n3 @@ -160,13 +173,13 @@ n3.next = n4 ```cpp title="linked_list.cpp" /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes -ListNode* n0 = new ListNode(1); -ListNode* n1 = new ListNode(3); -ListNode* n2 = new ListNode(2); -ListNode* n3 = new ListNode(5); -ListNode* n4 = new ListNode(4); -// Link the nodes with references +// Initialize the individual nodes +ListNode *n0 = new ListNode(1); +ListNode *n1 = new ListNode(3); +ListNode *n2 = new ListNode(2); +ListNode *n3 = new ListNode(5); +ListNode *n4 = new ListNode(4); +// Set up references between the nodes n0->next = n1; n1->next = n2; n2->next = n3; @@ -175,13 +188,13 @@ n3->next = n4; ```java title="linked_list.java" /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes +// Initialize the individual nodes ListNode n0 = new ListNode(1); ListNode n1 = new ListNode(3); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(5); ListNode n4 = new ListNode(4); -// Link the nodes with references +// Set up references between the nodes n0.next = n1; n1.next = n2; n2.next = n3; @@ -189,14 +202,14 @@ n3.next = n4; ``` ```csharp title="linked_list.cs" -/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes +// Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 +// Initialize the individual nodes ListNode n0 = new(1); ListNode n1 = new(3); ListNode n2 = new(2); ListNode n3 = new(5); ListNode n4 = new(4); -// Link the nodes with references +// Set up references between the nodes n0.next = n1; n1.next = n2; n2.next = n3; @@ -205,13 +218,14 @@ n3.next = n4; ```go title="linked_list.go" /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes +// Initialize the individual nodes n0 := NewListNode(1) n1 := NewListNode(3) n2 := NewListNode(2) n3 := NewListNode(5) n4 := NewListNode(4) -// Link the nodes with references + +// Set up references between the nodes n0.Next = n1 n1.Next = n2 n2.Next = n3 @@ -220,13 +234,13 @@ n3.Next = n4 ```swift title="linked_list.swift" /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes +// Initialize the individual nodes let n0 = ListNode(x: 1) let n1 = ListNode(x: 3) let n2 = ListNode(x: 2) let n3 = ListNode(x: 5) let n4 = ListNode(x: 4) -// Link the nodes with references +// Set up references between the nodes n0.next = n1 n1.next = n2 n2.next = n3 @@ -235,13 +249,13 @@ n3.next = n4 ```javascript title="linked_list.js" /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes +// Initialize the individual nodes const n0 = new ListNode(1); const n1 = new ListNode(3); const n2 = new ListNode(2); const n3 = new ListNode(5); const n4 = new ListNode(4); -// Link the nodes with references +// Set up references between the nodes n0.next = n1; n1.next = n2; n2.next = n3; @@ -250,13 +264,13 @@ n3.next = n4; ```typescript title="linked_list.ts" /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes +// Initialize the individual nodes const n0 = new ListNode(1); const n1 = new ListNode(3); const n2 = new ListNode(2); const n3 = new ListNode(5); const n4 = new ListNode(4); -// Link the nodes with references +// Set up references between the nodes n0.next = n1; n1.next = n2; n2.next = n3; @@ -264,14 +278,14 @@ n3.next = n4; ``` ```dart title="linked_list.dart" -/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes +// Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 +// Initialize the individual nodes ListNode n0 = ListNode(1); ListNode n1 = ListNode(3); ListNode n2 = ListNode(2); ListNode n3 = ListNode(5); ListNode n4 = ListNode(4); -// Link the nodes with references +// Set up references between the nodes n0.next = n1; n1.next = n2; n2.next = n3; @@ -280,14 +294,14 @@ n3.next = n4; ```rust title="linked_list.rs" /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes -let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); -let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); -let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); -let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); -let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); +// Initialize the individual nodes +let n0 = ListNode::new(1); +let n1 = ListNode::new(3); +let n2 = ListNode::new(2); +let n3 = ListNode::new(5); +let n4 = ListNode::new(4); -// Link the nodes with references +// Set up references between the nodes n0.borrow_mut().next = Some(n1.clone()); n1.borrow_mut().next = Some(n2.clone()); n2.borrow_mut().next = Some(n3.clone()); @@ -296,13 +310,13 @@ n3.borrow_mut().next = Some(n4.clone()); ```c title="linked_list.c" /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes -ListNode* n0 = newListNode(1); -ListNode* n1 = newListNode(3); -ListNode* n2 = newListNode(2); -ListNode* n3 = newListNode(5); -ListNode* n4 = newListNode(4); -// Link the nodes with references +// Initialize the individual nodes +ListNode *n0 = newListNode(1); +ListNode *n1 = newListNode(3); +ListNode *n2 = newListNode(2); +ListNode *n3 = newListNode(5); +ListNode *n4 = newListNode(4); +// Set up references between the nodes n0->next = n1; n1->next = n2; n2->next = n3; @@ -311,28 +325,29 @@ n3->next = n4; ```kotlin title="linked_list.kt" /* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */ -// Initialize the nodes +// Initialize the individual nodes val n0 = ListNode(1) val n1 = ListNode(3) val n2 = ListNode(2) val n3 = ListNode(5) val n4 = ListNode(4) -// Link the nodes with references -n0.next = n1; -n1.next = n2; -n2.next = n3; -n3.next = n4; + +// Set up references between the nodes +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 ``` ```ruby title="linked_list.rb" # Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 -# Initialize the nodes +# Initialize the individual nodes n0 = ListNode.new(1) n1 = ListNode.new(3) n2 = ListNode.new(2) n3 = ListNode.new(5) n4 = ListNode.new(4) -# Link the nodes with references +# Set up references between the nodes n0.next = n1 n1.next = n2 n2.next = n3 @@ -345,39 +360,46 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2 ```python title="" class ListNode: - """Doubly linked list node class""" + """Doubly linked list node""" + def __init__(self, val: int): - self.val: int = val # Node value - self.next: ListNode | None = None # Reference to the successor - self.prev: ListNode | None = None # Reference to the predecessor + """Constructor""" + self.val: int = val # Node value + self.next: ListNode | None = None # Reference to the next node + self.prev: ListNode | None = None # Reference to the previous node ``` ```cpp title="" -/* Doubly linked list node structure */ -struct ListNode { - int val; // Node value - ListNode *next; // Pointer to the successor - ListNode *prev; // Pointer to the predecessor - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // Constructor +/* Doubly linked list node */ +struct DoublyListNode { + int val; // Node value + DoublyListNode *next; // Pointer to the next node + DoublyListNode *prev; // Pointer to the previous node + DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { + } }; ``` ```java title="" -/* Doubly linked list node class */ +/* Doubly linked list node */ class ListNode { - int val; // Node value - ListNode next; // Reference to the successor - ListNode prev; // Reference to the predecessor - ListNode(int x) { val = x; } // Constructor + int val; // Node value + ListNode next; // Reference to the next node + ListNode prev; // Reference to the previous node + + ListNode(int val) { + this.val = val; + prev = next = null; + } } ``` ```csharp title="" -/* Doubly linked list node class */ -class ListNode(int x) { // Constructor - public int val = x; // Node value - public ListNode? next; // Reference to the successor - public ListNode? prev; // Reference to the predecessor +/* Doubly linked list node */ +public class ListNode(int val) { + public int val = val; // Node value + public ListNode? next = null; // Reference to the next node + public ListNode? prev = null; // Reference to the previous node } ``` @@ -400,117 +422,119 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* Doubly linked list node class */ +/* Doubly linked list node */ class ListNode { var val: Int // Node value - var next: ListNode? // Reference to the successor - var prev: ListNode? // Reference to the predecessor + var next: ListNode? // Reference to the next node + weak var prev: ListNode? // Reference to the previous node - init(x: Int) { // Constructor - val = x + init(val: Int) { + self.val = val } } ``` ```javascript title="" -/* Doubly linked list node class */ +/* Doubly linked list node */ class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // Node value - this.next = next === undefined ? null : next; // Reference to the successor - this.prev = prev === undefined ? null : prev; // Reference to the predecessor + prev; // Reference (pointer) to the previous node + next; // Reference (pointer) to the next node + val; // Node value + + constructor(val) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```typescript title="" -/* Doubly linked list node class */ +/* Doubly linked list node */ class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // Node value - this.next = next === undefined ? null : next; // Reference to the successor - this.prev = prev === undefined ? null : prev; // Reference to the predecessor + prev: ListNode | null; // Reference (pointer) to the previous node + next: ListNode | null; // Reference (pointer) to the next node + val: number; // Node value + + constructor(val: number) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```dart title="" -/* Doubly linked list node class */ +/* Doubly linked list node */ class ListNode { - int val; // Node value - ListNode? next; // Reference to the successor - ListNode? prev; // Reference to the predecessor - ListNode(this.val, [this.next, this.prev]); // Constructor + int val; // Node value + ListNode? next; // Reference to the next node + ListNode? prev; // Reference to the previous node + + ListNode(this.val, {this.next, this.prev}); } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; -/* Doubly linked list node type */ -#[derive(Debug)] -struct ListNode { - val: i32, // Node value - next: Option>>, // Pointer to the successor - prev: Option>>, // Pointer to the predecessor +/* Doubly linked list node */ +pub struct ListNode { + pub val: T, // Node value + pub next: Option>>>, // Pointer to the next node + pub prev: Option>>>, // Pointer to the previous node } -/* Constructor */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None, prev: None, - } + })) } } ``` ```c title="" -/* Doubly linked list node structure */ -typedef struct ListNode { - int val; // Node value - struct ListNode *next; // Pointer to the successor - struct ListNode *prev; // Pointer to the predecessor -} ListNode; +/* Doubly linked list node */ +typedef struct DoublyListNode { + int val; // Node value + struct DoublyListNode *next; // Pointer to the next node + struct DoublyListNode *prev; // Pointer to the previous node +} DoublyListNode; /* Constructor */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; +DoublyListNode *newDoublyListNode(int num) { + DoublyListNode *new = (DoublyListNode *)malloc(sizeof(DoublyListNode)); + new->val = num; + new->next = NULL; + new->prev = NULL; + return new; } ``` ```kotlin title="" -/* Doubly linked list node class */ -// Constructor -class ListNode(x: Int) { - val _val: Int = x // Node value - var next: ListNode? = null // Reference to the successor - var prev: ListNode? = null // Reference to the predecessor +/* Doubly linked list node */ +class ListNode( + var _val: Int // The node value is stored in _val +) { + var next: ListNode? = null // Reference to the next node + var prev: ListNode? = null // Reference to the previous node } ``` ```ruby title="" -# Doubly linked list node class +### Doubly linked list node ### class ListNode - attr_accessor :val # Node value - attr_accessor :next # Reference to the successor - attr_accessor :prev # Reference to the predecessor + attr_accessor :val # Node value + attr_accessor :next # Reference to the next node + attr_accessor :prev # Reference to the previous node - def initialize(val=0, next_node=nil, prev_node=nil) + ### Constructor ### + def initialize(val) @val = val - @next = next_node - @prev = prev_node end end ``` diff --git a/en/codes/snippets/chapter_array_and_linkedlist/list.md b/en/codes/snippets/chapter_array_and_linkedlist/list.md index d6705a45f..b254c4a25 100644 --- a/en/codes/snippets/chapter_array_and_linkedlist/list.md +++ b/en/codes/snippets/chapter_array_and_linkedlist/list.md @@ -1,83 +1,82 @@ ```python title="list.py" -# Initialize lists +# Initialize the list # Without initial values -nums1: list[int] = [] +empty_nums: list[int] = [] # With initial values nums: list[int] = [1, 3, 2, 5, 4] ``` ```cpp title="list.cpp" -/* Initialize lists */ -// In C++, vector is the list type used for nums here +/* Initialize the list */ // Without initial values -vector nums1; +vector emptyNums; // With initial values -vector nums = { 1, 3, 2, 5, 4 }; +vector nums = {1, 3, 2, 5, 4}; ``` ```java title="list.java" -/* Initialize lists */ +/* Initialize the list */ // Without initial values -List nums1 = new ArrayList<>(); -// With initial values (use Integer[], the boxed counterpart of int[]) +List emptyNums = new ArrayList<>(); +// With initial values (note that the array type must be Integer[] rather than int[], because list elements must use Integer, the wrapper class for int) Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); ``` ```csharp title="list.cs" -/* Initialize lists */ +/* Initialize the list */ // Without initial values -List nums1 = []; +List emptyNums = []; // With initial values int[] numbers = [1, 3, 2, 5, 4]; List nums = [.. numbers]; ``` ```go title="list_test.go" -/* Initialize lists */ +/* Initialize the list */ // Without initial values -nums1 := []int{} +emptyNums := []int{} // With initial values nums := []int{1, 3, 2, 5, 4} ``` ```swift title="list.swift" -/* Initialize lists */ +/* Initialize the list */ // Without initial values -let nums1: [Int] = [] +let emptyNums: [Int] = [] // With initial values var nums = [1, 3, 2, 5, 4] ``` ```javascript title="list.js" -/* Initialize lists */ +/* Initialize the list */ // Without initial values -const nums1 = []; +const emptyNums = []; // With initial values const nums = [1, 3, 2, 5, 4]; ``` ```typescript title="list.ts" -/* Initialize lists */ +/* Initialize the list */ // Without initial values -const nums1: number[] = []; +const emptyNums: number[] = []; // With initial values const nums: number[] = [1, 3, 2, 5, 4]; ``` ```dart title="list.dart" -/* Initialize lists */ +/* Initialize the list */ // Without initial values -List nums1 = []; +List emptyNums = []; // With initial values List nums = [1, 3, 2, 5, 4]; ``` ```rust title="list.rs" -/* Initialize lists */ +// Initialize the list // Without initial values -let nums1: Vec = Vec::new(); +let empty_nums: Vec = Vec::new(); // With initial values let mut nums: Vec = vec![1, 3, 2, 5, 4]; ``` @@ -87,64 +86,63 @@ let mut nums: Vec = vec![1, 3, 2, 5, 4]; ``` ```kotlin title="list.kt" -/* Initialize lists */ +/* Initialize the list */ // Without initial values -var nums1 = listOf() +val emptyNums = mutableListOf() // With initial values -var numbers = arrayOf(1, 3, 2, 5, 4) -var nums = numbers.toMutableList() +val nums = mutableListOf(1, 3, 2, 5, 4) ``` ```ruby title="list.rb" -# Initialize lists +# Initialize the list # Without initial values -nums1 = [] +empty_nums = [] # With initial values nums = [1, 3, 2, 5, 4] ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20%23%20Without%20initial%20values%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20%23%20Without%20initial%20values%0A%20%20%20%20empty_nums%20%3D%20%5B%5D%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" # Access an element -num: int = nums[1] # Access the element at index 1 +x: int = nums[1] # Access the element at index 1 # Update an element -nums[1] = 0 # Set the element at index 1 to 0 +nums[1] = 0 # Update the element at index 1 to 0 ``` ```cpp title="list.cpp" /* Access an element */ -int num = nums[1]; // Access the element at index 1 +int num = nums[1]; // Access the element at index 1 /* Update an element */ -nums[1] = 0; // Set the element at index 1 to 0 +nums[1] = 0; // Update the element at index 1 to 0 ``` ```java title="list.java" /* Access an element */ -int num = nums.get(1); // Access the element at index 1 +int num = nums.get(1); // Access the element at index 1 /* Update an element */ -nums.set(1, 0); // Set the element at index 1 to 0 +nums.set(1, 0); // Update the element at index 1 to 0 ``` ```csharp title="list.cs" /* Access an element */ -int num = nums[1]; // Access the element at index 1 +int num = nums[1]; // Access the element at index 1 /* Update an element */ -nums[1] = 0; // Set the element at index 1 to 0 +nums[1] = 0; // Update the element at index 1 to 0 ``` ```go title="list_test.go" /* Access an element */ -num := nums[1] // Access the element at index 1 +num := nums[1] // Access the element at index 1 /* Update an element */ -nums[1] = 0 // Set the element at index 1 to 0 +nums[1] = 0 // Update the element at index 1 to 0 ``` ```swift title="list.swift" @@ -152,38 +150,39 @@ nums[1] = 0 // Set the element at index 1 to 0 let num = nums[1] // Access the element at index 1 /* Update an element */ -nums[1] = 0 // Set the element at index 1 to 0 +nums[1] = 0 // Update the element at index 1 to 0 ``` ```javascript title="list.js" /* Access an element */ -const num = nums[1]; // Access the element at index 1 +const num = nums[1]; // Access the element at index 1 /* Update an element */ -nums[1] = 0; // Set the element at index 1 to 0 +nums[1] = 0; // Update the element at index 1 to 0 ``` ```typescript title="list.ts" /* Access an element */ -const num: number = nums[1]; // Access the element at index 1 +const num: number = nums[1]; // Access the element at index 1 /* Update an element */ -nums[1] = 0; // Set the element at index 1 to 0 +nums[1] = 0; // Update the element at index 1 to 0 ``` ```dart title="list.dart" /* Access an element */ -int num = nums[1]; // Access the element at index 1 +int _num = nums[1]; // Access the element at index 1 /* Update an element */ -nums[1] = 0; // Set the element at index 1 to 0 +nums[1] = 0; // Update the element at index 1 to 0 ``` ```rust title="list.rs" -/* Access an element */ -let num: i32 = nums[1]; // Access the element at index 1 -/* Update an element */ -nums[1] = 0; // Set the element at index 1 to 0 +// Access an element +let num = nums[1]; // Access the element at index 1 + +// Update an element +nums[1] = 0; // Update the element at index 1 to 0 ``` ```c title="list.c" @@ -192,27 +191,29 @@ nums[1] = 0; // Set the element at index 1 to 0 ```kotlin title="list.kt" /* Access an element */ -val num = nums[1] // Access the element at index 1 +val num = nums[1] // Access the element at index 1 + /* Update an element */ -nums[1] = 0 // Set the element at index 1 to 0 +nums[1] = 0 // Update the element at index 1 to 0 ``` ```ruby title="list.rb" # Access an element num = nums[1] # Access the element at index 1 + # Update an element -nums[1] = 0 # Set the element at index 1 to 0 +nums[1] = 0 # Update the element at index 1 to 0 ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20Access%20an%20element%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20Access%20the%20element%20at%20index%201%0A%0A%20%20%20%20%23%20Update%20an%20element%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20Set%20the%20element%20at%20index%201%20to%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20Access%20an%20element%0A%20%20%20%20x%20%3D%20nums%5B1%5D%20%20%23%20Access%20the%20element%20at%20index%201%0A%0A%20%20%20%20%23%20Update%20an%20element%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20Set%20the%20element%20at%20index%201%20to%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" # Clear the list nums.clear() -# Append elements +# Append an element at the end nums.append(1) nums.append(3) nums.append(2) @@ -220,17 +221,17 @@ nums.append(5) nums.append(4) # Insert an element in the middle -nums.insert(3, 6) # Insert 6 at index 3 +nums.insert(3, 6) # Insert the number 6 at index 3 # Remove an element -nums.pop(3) # Remove the element at index 3 +nums.pop(3) # Remove the element at index 3 ``` ```cpp title="list.cpp" /* Clear the list */ nums.clear(); -/* Append elements */ +/* Append an element at the end */ nums.push_back(1); nums.push_back(3); nums.push_back(2); @@ -238,17 +239,17 @@ nums.push_back(5); nums.push_back(4); /* Insert an element in the middle */ -nums.insert(nums.begin() + 3, 6); // Insert 6 at index 3 +nums.insert(nums.begin() + 3, 6); // Insert the number 6 at index 3 /* Remove an element */ -nums.erase(nums.begin() + 3); // Remove the element at index 3 +nums.erase(nums.begin() + 3); // Remove the element at index 3 ``` ```java title="list.java" /* Clear the list */ nums.clear(); -/* Append elements */ +/* Append at the end */ nums.add(1); nums.add(3); nums.add(2); @@ -256,17 +257,17 @@ nums.add(5); nums.add(4); /* Insert an element in the middle */ -nums.add(3, 6); // Insert 6 at index 3 +nums.add(3, 6); // Insert the number 6 at index 3 /* Remove an element */ -nums.remove(3); // Remove the element at index 3 +nums.remove(3); // Remove the element at index 3 ``` ```csharp title="list.cs" /* Clear the list */ nums.Clear(); -/* Append elements */ +/* Append at the end */ nums.Add(1); nums.Add(3); nums.Add(2); @@ -274,17 +275,17 @@ nums.Add(5); nums.Add(4); /* Insert an element in the middle */ -nums.Insert(3, 6); // Insert 6 at index 3 +nums.Insert(3, 6); // Insert the number 6 at index 3 /* Remove an element */ -nums.RemoveAt(3); // Remove the element at index 3 +nums.RemoveAt(3); // Remove the element at index 3 ``` ```go title="list_test.go" /* Clear the list */ nums = nil -/* Append elements */ +/* Append at the end */ nums = append(nums, 1) nums = append(nums, 3) nums = append(nums, 2) @@ -292,7 +293,7 @@ nums = append(nums, 5) nums = append(nums, 4) /* Insert an element in the middle */ -nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert 6 at index 3 +nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert the number 6 at index 3 /* Remove an element */ nums = append(nums[:3], nums[4:]...) // Remove the element at index 3 @@ -302,7 +303,7 @@ nums = append(nums[:3], nums[4:]...) // Remove the element at index 3 /* Clear the list */ nums.removeAll() -/* Append elements */ +/* Append at the end */ nums.append(1) nums.append(3) nums.append(2) @@ -310,7 +311,7 @@ nums.append(5) nums.append(4) /* Insert an element in the middle */ -nums.insert(6, at: 3) // Insert 6 at index 3 +nums.insert(6, at: 3) // Insert the number 6 at index 3 /* Remove an element */ nums.remove(at: 3) // Remove the element at index 3 @@ -320,7 +321,7 @@ nums.remove(at: 3) // Remove the element at index 3 /* Clear the list */ nums.length = 0; -/* Append elements */ +/* Append an element at the end */ nums.push(1); nums.push(3); nums.push(2); @@ -328,17 +329,17 @@ nums.push(5); nums.push(4); /* Insert an element in the middle */ -nums.splice(3, 0, 6); // Insert 6 at index 3 +nums.splice(3, 0, 6); // Insert the number 6 at index 3 /* Remove an element */ -nums.splice(3, 1); // Remove the element at index 3 +nums.splice(3, 1); // Remove the element at index 3 ``` ```typescript title="list.ts" /* Clear the list */ nums.length = 0; -/* Append elements */ +/* Append an element at the end */ nums.push(1); nums.push(3); nums.push(2); @@ -346,17 +347,17 @@ nums.push(5); nums.push(4); /* Insert an element in the middle */ -nums.splice(3, 0, 6); // Insert 6 at index 3 +nums.splice(3, 0, 6); // Insert the number 6 at index 3 /* Remove an element */ -nums.splice(3, 1); // Remove the element at index 3 +nums.splice(3, 1); // Remove the element at index 3 ``` ```dart title="list.dart" /* Clear the list */ nums.clear(); -/* Append elements */ +/* Append an element at the end */ nums.add(1); nums.add(3); nums.add(2); @@ -364,28 +365,28 @@ nums.add(5); nums.add(4); /* Insert an element in the middle */ -nums.insert(3, 6); // Insert 6 at index 3 +nums.insert(3, 6); // Insert the number 6 at index 3 /* Remove an element */ nums.removeAt(3); // Remove the element at index 3 ``` ```rust title="list.rs" -/* Clear the list */ +// Clear the list nums.clear(); -/* Append elements */ +// Append an element at the end nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* Insert an element in the middle */ -nums.insert(3, 6); // Insert 6 at index 3 +// Insert an element in the middle +nums.insert(3, 6); // Insert the number 6 at index 3 -/* Remove an element */ -nums.remove(3); // Remove the element at index 3 +// Remove an element +nums.remove(3); // Remove the element at index 3 ``` ```c title="list.c" @@ -394,27 +395,27 @@ nums.remove(3); // Remove the element at index 3 ```kotlin title="list.kt" /* Clear the list */ -nums.clear(); +nums.clear() -/* Append elements */ -nums.add(1); -nums.add(3); -nums.add(2); -nums.add(5); -nums.add(4); +/* Append at the end */ +nums.add(1) +nums.add(3) +nums.add(2) +nums.add(5) +nums.add(4) /* Insert an element in the middle */ -nums.add(3, 6); // Insert 6 at index 3 +nums.add(3, 6) // Insert the number 6 at index 3 /* Remove an element */ -nums.removeAt(3); // Remove the element at index 3 +nums.removeAt(3) // Remove the element at index 3 ``` ```ruby title="list.rb" # Clear the list nums.clear -# Append elements +# Append an element at the end nums << 1 nums << 3 nums << 2 @@ -422,7 +423,7 @@ nums << 5 nums << 4 # Insert an element in the middle -nums.insert(3, 6) # Insert 6 at index 3 +nums.insert(3, 6) # Insert the number 6 at index 3 # Remove an element nums.delete_at(3) # Remove the element at index 3 @@ -438,7 +439,7 @@ count = 0 for i in range(len(nums)): count += nums[i] -# Traverse list elements directly +# Iterate directly over the list elements for num in nums: count += num ``` @@ -450,10 +451,10 @@ for (int i = 0; i < nums.size(); i++) { count += nums[i]; } -/* Traverse list elements directly */ +/* Iterate directly over the list elements */ count = 0; -for (int num : nums) { - count += num; +for (int x : nums) { + count += x; } ``` @@ -464,9 +465,9 @@ for (int i = 0; i < nums.size(); i++) { count += nums.get(i); } -/* Traverse list elements directly */ -for (int num : nums) { - count += num; +/* Iterate directly over the list elements */ +for (int x : nums) { + count += x; } ``` @@ -477,10 +478,10 @@ for (int i = 0; i < nums.Count; i++) { count += nums[i]; } -/* Traverse list elements directly */ +/* Iterate directly over the list elements */ count = 0; -foreach (int num in nums) { - count += num; +foreach (int x in nums) { + count += x; } ``` @@ -491,10 +492,10 @@ for i := 0; i < len(nums); i++ { count += nums[i] } -/* Traverse list elements directly */ +/* Iterate directly over the list elements */ count = 0 -for _, num := range nums { - count += num +for _, x := range nums { + count += x } ``` @@ -505,10 +506,10 @@ for i in nums.indices { count += nums[i] } -/* Traverse list elements directly */ +/* Iterate directly over the list elements */ count = 0 -for num in nums { - count += num +for x in nums { + count += x } ``` @@ -519,10 +520,10 @@ for (let i = 0; i < nums.length; i++) { count += nums[i]; } -/* Traverse list elements directly */ +/* Iterate directly over the list elements */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` @@ -533,10 +534,10 @@ for (let i = 0; i < nums.length; i++) { count += nums[i]; } -/* Traverse list elements directly */ +/* Iterate directly over the list elements */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` @@ -544,13 +545,13 @@ for (const num of nums) { /* Traverse the list by index */ int count = 0; for (var i = 0; i < nums.length; i++) { - count += nums[i]; + count += nums[i]; } -/* Traverse list elements directly */ +/* Iterate directly over the list elements */ count = 0; -for (var num in nums) { - count += num; +for (var x in nums) { + count += x; } ``` @@ -561,10 +562,10 @@ for i in 0..nums.len() { _count += nums[i]; } -// Traverse list elements directly +// Iterate directly over the list elements _count = 0; -for num in &nums { - _count += num; +for x in &nums { + _count += x; } ``` @@ -579,9 +580,9 @@ for (i in nums.indices) { count += nums[i] } -/* Traverse list elements directly */ -for (num in nums) { - count += num +/* Iterate directly over the list elements */ +for (j in nums) { + count += j } ``` @@ -589,13 +590,13 @@ for (num in nums) { # Traverse the list by index count = 0 for i in 0...nums.length - count += nums[i] + count += nums[i] end -# Traverse list elements directly +# Iterate directly over the list elements count = 0 -for num in nums - count += num +nums.each do |x| + count += x end ``` @@ -605,63 +606,63 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 ```python title="list.py" # Concatenate two lists -nums1: list[int] = [6, 8, 7, 10, 9] -nums += nums1 # Append nums1 to nums +nums1 = [6, 8, 7, 10, 9] +nums += nums1 # Append list nums1 to nums ``` ```cpp title="list.cpp" /* Concatenate two lists */ -vector nums1 = { 6, 8, 7, 10, 9 }; -// Append nums1 to nums +vector nums1 = {6, 8, 7, 10, 9}; +// Append list nums1 to nums nums.insert(nums.end(), nums1.begin(), nums1.end()); ``` ```java title="list.java" /* Concatenate two lists */ List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); -nums.addAll(nums1); // Append nums1 to nums +nums.addAll(nums1); // Append list nums1 to nums ``` ```csharp title="list.cs" /* Concatenate two lists */ List nums1 = [6, 8, 7, 10, 9]; -nums.AddRange(nums1); // Append nums1 to nums +nums.AddRange(nums1); // Append list nums1 to nums ``` ```go title="list_test.go" /* Concatenate two lists */ nums1 := []int{6, 8, 7, 10, 9} -nums = append(nums, nums1...) // Append nums1 to nums +nums = append(nums, nums1...) // Append list nums1 to nums ``` ```swift title="list.swift" /* Concatenate two lists */ let nums1 = [6, 8, 7, 10, 9] -nums.append(contentsOf: nums1) // Append nums1 to nums +nums.append(contentsOf: nums1) // Append list nums1 to nums ``` ```javascript title="list.js" /* Concatenate two lists */ const nums1 = [6, 8, 7, 10, 9]; -nums.push(...nums1); // Append nums1 to nums +nums.push(...nums1); // Append list nums1 to nums ``` ```typescript title="list.ts" /* Concatenate two lists */ const nums1: number[] = [6, 8, 7, 10, 9]; -nums.push(...nums1); // Append nums1 to nums +nums.push(...nums1); // Append list nums1 to nums ``` ```dart title="list.dart" /* Concatenate two lists */ List nums1 = [6, 8, 7, 10, 9]; -nums.addAll(nums1); // Append nums1 to nums +nums.addAll(nums1); // Append list nums1 to nums ``` ```rust title="list.rs" -/* Concatenate two lists */ -let nums1: Vec = vec![6, 8, 7, 10, 9]; -nums.extend(nums1); +// Concatenate two lists +let mut nums1 = vec![6, 8, 7, 10, 9]; +nums.append(&mut nums1); // append moves the elements out of nums1, leaving nums1 empty ``` ```c title="list.c" @@ -670,8 +671,8 @@ nums.extend(nums1); ```kotlin title="list.kt" /* Concatenate two lists */ -val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() -nums.addAll(nums1) // Append nums1 to nums +val nums1 = mutableListOf(6, 8, 7, 10, 9) +nums.addAll(nums1) // Append list nums1 to nums ``` ```ruby title="list.rb" @@ -686,52 +687,52 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 ```python title="list.py" # Sort the list -nums.sort() # After sorting, elements are in ascending order +nums.sort() # After sorting, the list elements are in ascending order ``` ```cpp title="list.cpp" /* Sort the list */ -sort(nums.begin(), nums.end()); // After sorting, elements are in ascending order +sort(nums.begin(), nums.end()); // After sorting, the list elements are in ascending order ``` ```java title="list.java" /* Sort the list */ -Collections.sort(nums); // After sorting, elements are in ascending order +Collections.sort(nums); // After sorting, the list elements are in ascending order ``` ```csharp title="list.cs" /* Sort the list */ -nums.Sort(); // After sorting, elements are in ascending order +nums.Sort(); // After sorting, the list elements are in ascending order ``` ```go title="list_test.go" /* Sort the list */ -sort.Ints(nums) // After sorting, elements are in ascending order +sort.Ints(nums) // After sorting, the list elements are in ascending order ``` ```swift title="list.swift" /* Sort the list */ -nums.sort() // After sorting, elements are in ascending order +nums.sort() // After sorting, the list elements are in ascending order ``` ```javascript title="list.js" /* Sort the list */ -nums.sort((a, b) => a - b); // After sorting, elements are in ascending order +nums.sort((a, b) => a - b); // After sorting, the list elements are in ascending order ``` ```typescript title="list.ts" /* Sort the list */ -nums.sort((a, b) => a - b); // After sorting, elements are in ascending order +nums.sort((a, b) => a - b); // After sorting, the list elements are in ascending order ``` ```dart title="list.dart" /* Sort the list */ -nums.sort(); // After sorting, elements are in ascending order +nums.sort(); // After sorting, the list elements are in ascending order ``` ```rust title="list.rs" -/* Sort the list */ -nums.sort(); // After sorting, elements are in ascending order +// Sort the list +nums.sort(); // After sorting, the list elements are in ascending order ``` ```c title="list.c" @@ -740,12 +741,12 @@ nums.sort(); // After sorting, elements are in ascending order ```kotlin title="list.kt" /* Sort the list */ -nums.sort() // After sorting, elements are in ascending order +nums.sort() // After sorting, the list elements are in ascending order ``` ```ruby title="list.rb" # Sort the list -nums = nums.sort { |a, b| a <=> b } # After sorting, elements are in ascending order +nums = nums.sort { |a, b| a <=> b } # After sorting, the list elements are in ascending order ``` diff --git a/en/codes/snippets/chapter_hashing/hash_algorithm.md b/en/codes/snippets/chapter_hashing/hash_algorithm.md index 8c702b736..136d50571 100644 --- a/en/codes/snippets/chapter_hashing/hash_algorithm.md +++ b/en/codes/snippets/chapter_hashing/hash_algorithm.md @@ -2,100 +2,122 @@ ```python title="built_in_hash.py" num = 3 hash_num = hash(num) -# The hash of the integer 3 is 3 +print(f"Integer {num} has hash value {hash_num}") +# Integer 3 has hash value 3 bol = True hash_bol = hash(bol) -# The hash of the Boolean True is 1 +print(f"Boolean {bol} has hash value {hash_bol}") +# Boolean True has hash value 1 dec = 3.14159 hash_dec = hash(dec) -# The hash of the floating-point number 3.14159 is 326484311674566659 +print(f"Floating-point number {dec} has hash value {hash_dec}") +# Floating-point number 3.14159 has hash value 326484311674566659 str = "Hello 算法" hash_str = hash(str) -# The hash of the string “Hello 算法” is 4617003410720528961 +print(f"String '{str}' has hash value {hash_str}") +# String 'Hello 算法' has hash value 4617003410720528961 tup = (12836, "小哈") hash_tup = hash(tup) -# The hash of the tuple (12836, '小哈') is 1029005403108185979 +print(f"Tuple {tup} has hash value {hash_tup}") +# Tuple (12836, '小哈') has hash value 1029005403108185979 obj = ListNode(0) hash_obj = hash(obj) -# The hash of the node object is 274267521 +print(f"Node object {obj} has hash value {hash_obj}") +# Node object has hash value 274267521 ``` ```cpp title="built_in_hash.cpp" int num = 3; size_t hashNum = hash()(num); -// The hash of the integer 3 is 3 +cout << "Integer " << num << " has hash value " << hashNum << "\n"; +// Integer 3 has hash value 3 bool bol = true; size_t hashBol = hash()(bol); -// The hash of the Boolean 1 is 1 +cout << "Boolean " << bol << " has hash value " << hashBol << "\n"; +// Boolean 1 has hash value 1 double dec = 3.14159; size_t hashDec = hash()(dec); -// The hash of the floating-point number 3.14159 is 4614256650576692846 +cout << "Floating-point number " << dec << " has hash value " << hashDec << "\n"; +// Floating-point number 3.14159 has hash value 4614256650576692846 string str = "Hello 算法"; size_t hashStr = hash()(str); -// The hash of the string “Hello 算法” is 15466937326284535026 +cout << "String '" << str << "' has hash value " << hashStr << "\n"; +// String 'Hello 算法' has hash value 15466937326284535026 -// In C++, built-in std::hash() provides hashing only for basic data types -// Hashing for arrays and objects must be implemented separately +// In C++, the built-in std::hash() only computes hash values for basic data types +// Hashing arrays and objects requires a custom implementation ``` ```java title="built_in_hash.java" int num = 3; int hashNum = Integer.hashCode(num); -// The hash of the integer 3 is 3 +System.out.println("Integer " + num + " has hash value " + hashNum); +// Integer 3 has hash value 3 boolean bol = true; int hashBol = Boolean.hashCode(bol); -// The hash of the Boolean true is 1231 +System.out.println("Boolean " + bol + " has hash value " + hashBol); +// Boolean true has hash value 1231 double dec = 3.14159; int hashDec = Double.hashCode(dec); -// The hash of the floating-point number 3.14159 is -1340954729 +System.out.println("Floating-point number " + dec + " has hash value " + hashDec); +// Floating-point number 3.14159 has hash value -1340954729 String str = "Hello 算法"; int hashStr = str.hashCode(); -// The hash of the string “Hello 算法” is -727081396 +System.out.println("String '" + str + "' has hash value " + hashStr); +// String 'Hello 算法' has hash value -727081396 Object[] arr = { 12836, "小哈" }; -int hashTup = Arrays.hashCode(arr); -// The hash of the array [12836, 小哈] is 1151158 +int hashArr = Arrays.hashCode(arr); +System.out.println("Array " + Arrays.toString(arr) + " has hash value " + hashArr); +// Array [12836, 小哈] has hash value 1151158 ListNode obj = new ListNode(0); int hashObj = obj.hashCode(); -// The hash of the node object utils.ListNode@7dc5e7b4 is 2110121908 +System.out.println("Node object " + obj + " has hash value " + hashObj); +// Node object utils.ListNode@7dc5e7b4 has hash value 2110121908 ``` ```csharp title="built_in_hash.cs" int num = 3; int hashNum = num.GetHashCode(); -// The hash of the integer 3 is 3; +Console.WriteLine("Integer " + num + " has hash value " + hashNum); +// Integer 3 has hash value 3 bool bol = true; int hashBol = bol.GetHashCode(); -// The hash of the Boolean true is 1; +Console.WriteLine("Boolean " + bol + " has hash value " + hashBol); +// Boolean True has hash value 1 double dec = 3.14159; int hashDec = dec.GetHashCode(); -// The hash of the floating-point number 3.14159 is -1340954729; +Console.WriteLine("Floating-point number " + dec + " has hash value " + hashDec); +// Floating-point number 3.14159 has hash value -1340954729 string str = "Hello 算法"; int hashStr = str.GetHashCode(); -// The hash of the string “Hello 算法” is -586107568; +Console.WriteLine("String '" + str + "' has hash value " + hashStr); +// String 'Hello 算法' has hash value -586107568 object[] arr = [12836, "小哈"]; -int hashTup = arr.GetHashCode(); -// The hash of the array [12836, 小哈] is 42931033; +int hashArr = arr.GetHashCode(); +Console.WriteLine("Array [" + string.Join(", ", arr) + "] has hash value " + hashArr); +// Array [12836, 小哈] has hash value 42931033 ListNode obj = new(0); int hashObj = obj.GetHashCode(); -// The hash of the node object 0 is 39053774; +Console.WriteLine("Node object " + obj + " has hash value " + hashObj); +// Node object 0 has hash value 39053774 ``` ```go title="built_in_hash.go" @@ -105,27 +127,33 @@ int hashObj = obj.GetHashCode(); ```swift title="built_in_hash.swift" let num = 3 let hashNum = num.hashValue -// The hash of the integer 3 is 9047044699613009734 +print("Integer \(num) has hash value \(hashNum)") +// Integer 3 has hash value 9047044699613009734 let bol = true let hashBol = bol.hashValue -// The hash of the Boolean true is -4431640247352757451 +print("Boolean \(bol) has hash value \(hashBol)") +// Boolean true has hash value -4431640247352757451 let dec = 3.14159 let hashDec = dec.hashValue -// The hash of the floating-point number 3.14159 is -2465384235396674631 +print("Floating-point number \(dec) has hash value \(hashDec)") +// Floating-point number 3.14159 has hash value -2465384235396674631 let str = "Hello 算法" let hashStr = str.hashValue -// The hash of the string “Hello 算法” is -7850626797806988787 +print("String '\(str)' has hash value \(hashStr)") +// String 'Hello 算法' has hash value -7850626797806988787 let arr = [AnyHashable(12836), AnyHashable("小哈")] -let hashTup = arr.hashValue -// The hash of the array [AnyHashable(12836), AnyHashable("小哈")] is -2308633508154532996 +let hashArr = arr.hashValue +print("Array \(arr) has hash value \(hashArr)") +// Array [AnyHashable(12836), AnyHashable("小哈")] has hash value -2308633508154532996 let obj = ListNode(x: 0) let hashObj = obj.hashValue -// The hash of the node object utils.ListNode is -2434780518035996159 +print("Node object \(obj) has hash value \(hashObj)") +// Node object utils.ListNode has hash value -2434780518035996159 ``` ```javascript title="built_in_hash.js" @@ -139,27 +167,33 @@ let hashObj = obj.hashValue ```dart title="built_in_hash.dart" int num = 3; int hashNum = num.hashCode; -// The hash of the integer 3 is 34803 +print("Integer $num has hash value $hashNum"); +// Integer 3 has hash value 34803 bool bol = true; int hashBol = bol.hashCode; -// The hash of the Boolean true is 1231 +print("Boolean $bol has hash value $hashBol"); +// Boolean true has hash value 1231 double dec = 3.14159; int hashDec = dec.hashCode; -// The hash of the floating-point number 3.14159 is 2570631074981783 +print("Floating-point number $dec has hash value $hashDec"); +// Floating-point number 3.14159 has hash value 2570631074981783 String str = "Hello 算法"; int hashStr = str.hashCode; -// The hash of the string “Hello 算法” is 468167534 +print("String '$str' has hash value $hashStr"); +// String 'Hello 算法' has hash value 468167534 List arr = [12836, "小哈"]; int hashArr = arr.hashCode; -// The hash of the array [12836, 小哈] is 976512528 +print("Array $arr has hash value $hashArr"); +// Array [12836, 小哈] has hash value 976512528 -ListNode obj = new ListNode(0); +ListNode obj = ListNode(0); int hashObj = obj.hashCode; -// The hash of the node object Instance of 'ListNode' is 1033450432 +print("Node object $obj has hash value $hashObj"); +// Node object Instance of 'ListNode' has hash value 1033450432 ``` ```rust title="built_in_hash.rs" @@ -170,37 +204,43 @@ let num = 3; let mut num_hasher = DefaultHasher::new(); num.hash(&mut num_hasher); let hash_num = num_hasher.finish(); -// The hash of the integer 3 is 568126464209439262 +println!("Integer {} has hash value {}", num, hash_num); +// Integer 3 has hash value 568126464209439262 let bol = true; let mut bol_hasher = DefaultHasher::new(); bol.hash(&mut bol_hasher); let hash_bol = bol_hasher.finish(); -// The hash of the Boolean true is 4952851536318644461 +println!("Boolean {} has hash value {}", bol, hash_bol); +// Boolean true has hash value 4952851536318644461 let dec: f32 = 3.14159; let mut dec_hasher = DefaultHasher::new(); dec.to_bits().hash(&mut dec_hasher); let hash_dec = dec_hasher.finish(); -// The hash of the floating-point number 3.14159 is 2566941990314602357 +println!("Floating-point number {} has hash value {}", dec, hash_dec); +// Floating-point number 3.14159 has hash value 2566941990314602357 let str = "Hello 算法"; let mut str_hasher = DefaultHasher::new(); str.hash(&mut str_hasher); let hash_str = str_hasher.finish(); -// The hash of the string “Hello 算法” is 16092673739211250988 +println!("String '{}' has hash value {}", str, hash_str); +// String 'Hello 算法' has hash value 16092673739211250988 -let arr = (&12836, &"小哈"); +let tup = (&12836, &"小哈"); let mut tup_hasher = DefaultHasher::new(); -arr.hash(&mut tup_hasher); +tup.hash(&mut tup_hasher); let hash_tup = tup_hasher.finish(); -// The hash of the tuple (12836, "小哈") is 1885128010422702749 +println!("Tuple {:?} has hash value {}", tup, hash_tup); +// Tuple (12836, "小哈") has hash value 1885128010422702749 let node = ListNode::new(42); -let mut hasher = DefaultHasher::new(); -node.borrow().val.hash(&mut hasher); -let hash = hasher.finish(); -// The hash of the node object RefCell { value: ListNode { val: 42, next: None } } is 15387811073369036852 +let mut node_hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut node_hasher); +let hash_node = node_hasher.finish(); +println!("Node object {:?} has hash value {}", node, hash_node); +// Node object RefCell { value: ListNode { val: 42, next: None } } has hash value 15387811073369036852 ``` ```c title="built_in_hash.c" @@ -210,54 +250,66 @@ let hash = hasher.finish(); ```kotlin title="built_in_hash.kt" val num = 3 val hashNum = num.hashCode() -// The hash of the integer 3 is 3 +println("Integer $num has hash value $hashNum") +// Integer 3 has hash value 3 val bol = true val hashBol = bol.hashCode() -// The hash of the Boolean true is 1231 +println("Boolean $bol has hash value $hashBol") +// Boolean true has hash value 1231 val dec = 3.14159 val hashDec = dec.hashCode() -// The hash of the floating-point number 3.14159 is -1340954729 +println("Floating-point number $dec has hash value $hashDec") +// Floating-point number 3.14159 has hash value -1340954729 val str = "Hello 算法" val hashStr = str.hashCode() -// The hash of the string “Hello 算法” is -727081396 +println("String '$str' has hash value $hashStr") +// String 'Hello 算法' has hash value -727081396 val arr = arrayOf(12836, "小哈") -val hashTup = arr.hashCode() -// The hash of the array [12836, 小哈] is 189568618 +val hashArr = arr.contentHashCode() +println("Array ${arr.contentToString()} has hash value $hashArr") +// Array [12836, 小哈] has hash value 1151158 val obj = ListNode(0) val hashObj = obj.hashCode() -// The hash of the node object utils.ListNode@1d81eb93 is 495053715 +println("Node object $obj has hash value $hashObj") +// Node object utils.ListNode@1d81eb93 has hash value 495053715 ``` ```ruby title="built_in_hash.rb" num = 3 hash_num = num.hash -# The hash of the integer 3 is -4385856518450339636 +puts "Integer #{num} has hash value #{hash_num}" +# Integer 3 has hash value -4385856518450339636 bol = true hash_bol = bol.hash -# The hash of the Boolean true is -1617938112149317027 +puts "Boolean #{bol} has hash value #{hash_bol}" +# Boolean true has hash value -1617938112149317027 dec = 3.14159 hash_dec = dec.hash -# The hash of the floating-point number 3.14159 is -1479186995943067893 +puts "Floating-point number #{dec} has hash value #{hash_dec}" +# Floating-point number 3.14159 has hash value -1479186995943067893 str = "Hello 算法" hash_str = str.hash -# The hash of the string “Hello 算法” is -4075943250025831763 +puts "String '#{str}' has hash value #{hash_str}" +# String 'Hello 算法' has hash value -4075943250025831763 -tup = [12836, '小哈'] -hash_tup = tup.hash -# The hash of the tuple (12836, '小哈') is 1999544809202288822 +arr = [12836, '小哈'] +hash_arr = arr.hash +puts "Array #{arr} has hash value #{hash_arr}" +# Array [12836, "小哈"] has hash value 1999544809202288822 obj = ListNode.new(0) hash_obj = obj.hash -# The hash of the node object # is 4302940560806366381 +puts "Node object #{obj} has hash value #{hash_obj}" +# Node object # has hash value 4302940560806366381 ``` -https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked-list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20next%20node%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20integer%203%20is%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20Boolean%20True%20is%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20floating-point%20number%203.14159%20is%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20string%20%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%20is%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20tuple%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20is%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20node%20object%20%3CListNode%20object%20at%200x1058fd810%3E%20is%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked-list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20next%20node%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20print%28f%22Integer%20%7Bnum%7D%20has%20hash%20value%20%7Bhash_num%7D%22%29%0A%20%20%20%20%23%20Integer%203%20has%20hash%20value%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20print%28f%22Boolean%20%7Bbol%7D%20has%20hash%20value%20%7Bhash_bol%7D%22%29%0A%20%20%20%20%23%20Boolean%20True%20has%20hash%20value%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20print%28f%22Floating-point%20number%20%7Bdec%7D%20has%20hash%20value%20%7Bhash_dec%7D%22%29%0A%20%20%20%20%23%20Floating-point%20number%203.14159%20has%20hash%20value%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20print%28f%22String%20%27%7Bstr%7D%27%20has%20hash%20value%20%7Bhash_str%7D%22%29%0A%20%20%20%20%23%20String%20%27Hello%20%E7%AE%97%E6%B3%95%27%20has%20hash%20value%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20print%28f%22Tuple%20%7Btup%7D%20has%20hash%20value%20%7Bhash_tup%7D%22%29%0A%20%20%20%20%23%20Tuple%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20has%20hash%20value%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20print%28f%22Node%20object%20%7Bobj%7D%20has%20hash%20value%20%7Bhash_obj%7D%22%29%0A%20%20%20%20%23%20Node%20object%20%3Cmodules.list_node.ListNode%20object%20at%200x1058fd810%3E%20has%20hash%20value%20274267521%0A&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_hashing/hash_map.md b/en/codes/snippets/chapter_hashing/hash_map.md index 63adeb264..b0a6f6cb2 100644 --- a/en/codes/snippets/chapter_hashing/hash_map.md +++ b/en/codes/snippets/chapter_hashing/hash_map.md @@ -1,72 +1,72 @@ ```python title="hash_map.py" -# Initialize a hash table -hmap: dict = {} +# Initialize the hash table +hmap = dict[int, str]() -# Insertion -# Add key-value pairs (key, value) to the hash table +# Insert operation +# Insert the key-value pair (key, value) into the hash table hmap[12836] = "小哈" hmap[15937] = "小啰" hmap[16750] = "小算" hmap[13276] = "小法" hmap[10583] = "小鸭" -# Lookup +# Lookup operation # Look up key in the hash table to obtain value name: str = hmap[15937] -# Deletion -# Remove a key-value pair (key, value) from the hash table +# Remove operation +# Remove the key-value pair (key, value) from the hash table hmap.pop(10583) ``` ```cpp title="hash_map.cpp" -/* Initialize a hash table */ +/* Initialize the hash table */ unordered_map map; -/* Insertion */ -// Add key-value pairs (key, value) to the hash table +/* Insert operation */ +// Insert the key-value pair (key, value) into the hash table map[12836] = "小哈"; map[15937] = "小啰"; map[16750] = "小算"; map[13276] = "小法"; map[10583] = "小鸭"; -/* Lookup */ +/* Lookup operation */ // Look up key in the hash table to obtain value string name = map[15937]; -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table +/* Remove operation */ +// Remove the key-value pair (key, value) from the hash table map.erase(10583); ``` ```java title="hash_map.java" -/* Initialize a hash table */ +/* Initialize the hash table */ Map map = new HashMap<>(); -/* Insertion */ -// Add key-value pairs (key, value) to the hash table +/* Insert operation */ +// Insert the key-value pair (key, value) into the hash table map.put(12836, "小哈"); map.put(15937, "小啰"); map.put(16750, "小算"); map.put(13276, "小法"); map.put(10583, "小鸭"); -/* Lookup */ +/* Lookup operation */ // Look up key in the hash table to obtain value String name = map.get(15937); -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table +/* Remove operation */ +// Remove the key-value pair (key, value) from the hash table map.remove(10583); ``` ```csharp title="hash_map.cs" -/* Initialize a hash table */ +/* Initialize the hash table */ Dictionary map = new() { - /* Insertion */ - // Add key-value pairs (key, value) to the hash table + /* Insert operation */ + // Insert the key-value pair (key, value) into the hash table { 12836, "小哈" }, { 15937, "小啰" }, { 16750, "小算" }, @@ -74,144 +74,141 @@ Dictionary map = new() { { 10583, "小鸭" } }; -/* Lookup */ +/* Lookup operation */ // Look up key in the hash table to obtain value string name = map[15937]; -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table +/* Remove operation */ +// Remove the key-value pair (key, value) from the hash table map.Remove(10583); ``` ```go title="hash_map_test.go" -/* Initialize a hash table */ +/* Initialize the hash table */ hmap := make(map[int]string) -/* Insertion */ -// Add key-value pairs (key, value) to the hash table +/* Insert operation */ +// Insert the key-value pair (key, value) into the hash table hmap[12836] = "小哈" hmap[15937] = "小啰" hmap[16750] = "小算" hmap[13276] = "小法" hmap[10583] = "小鸭" -/* Lookup */ +/* Lookup operation */ // Look up key in the hash table to obtain value name := hmap[15937] -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table +/* Remove operation */ +// Remove the key-value pair (key, value) from the hash table delete(hmap, 10583) ``` ```swift title="hash_map.swift" -/* Initialize a hash table */ +/* Initialize the hash table */ var map: [Int: String] = [:] -/* Insertion */ -// Add key-value pairs (key, value) to the hash table +/* Insert operation */ +// Insert the key-value pair (key, value) into the hash table map[12836] = "小哈" map[15937] = "小啰" map[16750] = "小算" map[13276] = "小法" map[10583] = "小鸭" -/* Lookup */ +/* Lookup operation */ // Look up key in the hash table to obtain value let name = map[15937]! -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table +/* Remove operation */ +// Remove the key-value pair (key, value) from the hash table map.removeValue(forKey: 10583) ``` ```javascript title="hash_map.js" -/* Initialize a hash table */ +/* Initialize the hash table */ const map = new Map(); -/* Insertion */ -// Add key-value pairs (key, value) to the hash table + +/* Insert operation */ +// Insert the key-value pair (key, value) into the hash table map.set(12836, '小哈'); map.set(15937, '小啰'); map.set(16750, '小算'); map.set(13276, '小法'); map.set(10583, '小鸭'); -/* Lookup */ +/* Lookup operation */ // Look up key in the hash table to obtain value let name = map.get(15937); -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table +/* Remove operation */ +// Remove the key-value pair (key, value) from the hash table map.delete(10583); ``` ```typescript title="hash_map.ts" -/* Initialize a hash table */ +/* Initialize the hash table */ const map = new Map(); -/* Insertion */ -// Add key-value pairs (key, value) to the hash table + +/* Insert operation */ +// Insert the key-value pair (key, value) into the hash table map.set(12836, '小哈'); map.set(15937, '小啰'); map.set(16750, '小算'); map.set(13276, '小法'); map.set(10583, '小鸭'); -console.info('\nAfter insertion, the hash table is\nKey -> Value'); -console.info(map); -/* Lookup */ +/* Lookup operation */ // Look up key in the hash table to obtain value let name = map.get(15937); -console.info('\nLooking up student ID 15937 gives the name ' + name); -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table +/* Remove operation */ +// Remove the key-value pair (key, value) from the hash table map.delete(10583); -console.info('\nAfter deleting 10583, the hash table is\nKey -> Value'); -console.info(map); ``` ```dart title="hash_map.dart" -/* Initialize a hash table */ -Map map = {}; +/* Initialize the hash table */ +final Map map = {}; -/* Insertion */ -// Add key-value pairs (key, value) to the hash table +/* Insert operation */ +// Insert the key-value pair (key, value) into the hash table map[12836] = "小哈"; map[15937] = "小啰"; map[16750] = "小算"; map[13276] = "小法"; map[10583] = "小鸭"; -/* Lookup */ +/* Lookup operation */ // Look up key in the hash table to obtain value -String? name = map[15937]; +final String? name = map[15937]; -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table +/* Remove operation */ +// Remove the key-value pair (key, value) from the hash table map.remove(10583); ``` ```rust title="hash_map.rs" use std::collections::HashMap; -/* Initialize a hash table */ -let mut map: HashMap = HashMap::new(); +// Initialize the hash table +let mut map = HashMap::new(); -/* Insertion */ -// Add key-value pairs (key, value) to the hash table -map.insert(12836, "小哈".to_string()); -map.insert(15937, "小啰".to_string()); -map.insert(16750, "小算".to_string()); -map.insert(13276, "小法".to_string()); -map.insert(10583, "小鸭".to_string()); +// Insert operation +// Insert the key-value pair (key, value) into the hash table +map.insert(12836, "小哈"); +map.insert(15937, "小啰"); +map.insert(16750, "小算"); +map.insert(13276, "小法"); +map.insert(10583, "小鸭"); -/* Lookup */ +// Lookup operation // Look up key in the hash table to obtain value -let _name: Option<&String> = map.get(&15937); +let name = map.get(&15937).copied().unwrap(); -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table -let _removed_value: Option = map.remove(&10583); +// Remove operation +// Remove the key-value pair (key, value) from the hash table +_ = map.remove(&10583); ``` ```c title="hash_map.c" @@ -219,44 +216,44 @@ let _removed_value: Option = map.remove(&10583); ``` ```kotlin title="hash_map.kt" -/* Initialize a hash table */ -val map = HashMap() +/* Initialize the hash table */ +val map = HashMap() -/* Insertion */ -// Add key-value pairs (key, value) to the hash table +/* Insert operation */ +// Insert the key-value pair (key, value) into the hash table map[12836] = "小哈" map[15937] = "小啰" map[16750] = "小算" map[13276] = "小法" map[10583] = "小鸭" -/* Lookup */ +/* Lookup operation */ // Look up key in the hash table to obtain value val name = map[15937] -/* Deletion */ -// Remove a key-value pair (key, value) from the hash table +/* Remove operation */ +// Remove the key-value pair (key, value) from the hash table map.remove(10583) ``` ```ruby title="hash_map.rb" -# Initialize a hash table +# Initialize the hash table hmap = {} -# Insertion -# Add key-value pairs (key, value) to the hash table +# Insert operation +# Insert the key-value pair (key, value) into the hash table hmap[12836] = "小哈" hmap[15937] = "小啰" hmap[16750] = "小算" hmap[13276] = "小法" hmap[10583] = "小鸭" -# Lookup +# Lookup operation # Look up key in the hash table to obtain value name = hmap[15937] -# Deletion -# Remove a key-value pair (key, value) from the hash table +# Remove operation +# Remove the key-value pair (key, value) from the hash table hmap.delete(10583) ``` @@ -269,52 +266,59 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 # Traverse key-value pairs: key->value for key, value in hmap.items(): print(key, "->", value) + # Traverse keys only: key for key in hmap.keys(): print(key) + # Traverse values only: value -for value in hmap.values(): - print(value) +for val in hmap.values(): + print(val) ``` ```cpp title="hash_map.cpp" /* Traverse the hash table */ // Traverse key-value pairs: key->value -for (auto kv: map) { +for (auto kv : map) { cout << kv.first << " -> " << kv.second << endl; } -// Use an iterator to traverse key->value pairs + +// Traverse key->value using an iterator for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; + cout << iter->first << " -> " << iter->second << endl; } ``` ```java title="hash_map.java" /* Traverse the hash table */ // Traverse key-value pairs: key->value -for (Map.Entry kv: map.entrySet()) { +for (Map.Entry kv : map.entrySet()) { System.out.println(kv.getKey() + " -> " + kv.getValue()); } + // Traverse keys only: key -for (int key: map.keySet()) { +for (int key : map.keySet()) { System.out.println(key); } + // Traverse values only: value -for (String val: map.values()) { +for (String val : map.values()) { System.out.println(val); } ``` ```csharp title="hash_map.cs" /* Traverse the hash table */ -// Traverse key-value pairs: Key->Value +// Traverse key-value pairs: key->value foreach (var kv in map) { Console.WriteLine(kv.Key + " -> " + kv.Value); } + // Traverse keys only: key foreach (int key in map.Keys) { Console.WriteLine(key); } + // Traverse values only: value foreach (string val in map.Values) { Console.WriteLine(val); @@ -327,10 +331,12 @@ foreach (string val in map.Values) { for key, value := range hmap { fmt.Println(key, "->", value) } + // Traverse keys only: key for key := range hmap { fmt.Println(key) } + // Traverse values only: value for _, value := range hmap { fmt.Println(value) @@ -339,15 +345,17 @@ for _, value := range hmap { ```swift title="hash_map.swift" /* Traverse the hash table */ -// Traverse key-value pairs: Key->Value +// Traverse key-value pairs: key->value for (key, value) in map { print("\(key) -> \(value)") } -// Traverse keys only: Key + +// Traverse keys only: key for key in map.keys { print(key) } -// Traverse values only: Value + +// Traverse values only: value for value in map.values { print(value) } @@ -355,15 +363,17 @@ for value in map.values { ```javascript title="hash_map.js" /* Traverse the hash table */ -console.info('\nTraverse key-value pairs: Key->Value'); +// Traverse key-value pairs: key->value for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\nTraverse keys only: Key'); + +// Traverse keys only: key for (const k of map.keys()) { console.info(k); } -console.info('\nTraverse values only: Value'); + +// Traverse values only: value for (const v of map.values()) { console.info(v); } @@ -371,15 +381,17 @@ for (const v of map.values()) { ```typescript title="hash_map.ts" /* Traverse the hash table */ -console.info('\nTraverse key-value pairs: Key->Value'); +// Traverse key-value pairs: key->value for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\nTraverse keys only: Key'); + +// Traverse keys only: key for (const k of map.keys()) { console.info(k); } -console.info('\nTraverse values only: Value'); + +// Traverse values only: value for (const v of map.values()) { console.info(v); } @@ -387,35 +399,29 @@ for (const v of map.values()) { ```dart title="hash_map.dart" /* Traverse the hash table */ -// Traverse key-value pairs: Key->Value -map.forEach((key, value) { - print('$key -> $value'); -}); +// Traverse key-value pairs: key->value +map.forEach((key, value) => print("$key -> $value")); -// Traverse keys only: Key -map.keys.forEach((key) { - print(key); -}); +// Traverse keys only: key +map.keys.forEach((key) => print(key)); -// Traverse values only: Value -map.values.forEach((value) { - print(value); -}); +// Traverse values only: value +map.values.forEach((value) => print(value)); ``` ```rust title="hash_map.rs" -/* Traverse the hash table */ -// Traverse key-value pairs: Key->Value +// Traverse the hash table +// Traverse key-value pairs: key->value for (key, value) in &map { println!("{key} -> {value}"); } -// Traverse keys only: Key +// Traverse keys only: key for key in map.keys() { println!("{key}"); } -// Traverse values only: Value +// Traverse values only: value for value in map.values() { println!("{value}"); } @@ -431,10 +437,12 @@ for value in map.values() { for ((key, value) in map) { println("$key -> $value") } + // Traverse keys only: key for (key in map.keys) { println(key) } + // Traverse values only: value for (_val in map.values) { println(_val) @@ -454,4 +462,4 @@ hmap.values.each { |val| puts val } ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20hash%20table%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20Insertion%0A%20%20%20%20%23%20Add%20key-value%20pairs%20%28key%2C%20value%29%20to%20the%20hash%20table%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20Traverse%20the%20hash%20table%0A%20%20%20%20%23%20Traverse%20key-value%20pairs%3A%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20Traverse%20keys%20only%3A%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20Traverse%20values%20only%3A%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20hash%20table%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20Insertion%0A%20%20%20%20%23%20Add%20key-value%20pairs%20%28key%2C%20value%29%20to%20the%20hash%20table%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20Traverse%20the%20hash%20table%0A%20%20%20%20%23%20Traverse%20key-value%20pairs%3A%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20Traverse%20keys%20only%3A%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20Traverse%20values%20only%3A%20value%0A%20%20%20%20for%20val%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28val%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_heap/heap.md b/en/codes/snippets/chapter_heap/heap.md index b06e780f3..afb390e45 100644 --- a/en/codes/snippets/chapter_heap/heap.md +++ b/en/codes/snippets/chapter_heap/heap.md @@ -6,26 +6,26 @@ min_heap, flag = [], 1 max_heap, flag = [], -1 # Python's heapq module implements a min heap by default -# Negate elements before insertion to reverse their order and implement a max heap -# Here, flag = 1 gives a min heap and flag = -1 gives a max heap +# Negate each element before pushing it onto the heap to reverse the ordering and implement a max heap +# In this example, flag = 1 represents a min heap and flag = -1 represents a max heap -# Insert elements into the heap +# Push an element onto the heap heapq.heappush(max_heap, flag * 1) heapq.heappush(max_heap, flag * 3) heapq.heappush(max_heap, flag * 2) heapq.heappush(max_heap, flag * 5) heapq.heappush(max_heap, flag * 4) -# Access the root element -peek: int = flag * max_heap[0] # 5 +# Get the top element of the heap +peek: int = flag * max_heap[0] # 5 -# Remove root elements -# Removed elements form a descending sequence -val = flag * heapq.heappop(max_heap) # 5 -val = flag * heapq.heappop(max_heap) # 4 -val = flag * heapq.heappop(max_heap) # 3 -val = flag * heapq.heappop(max_heap) # 2 -val = flag * heapq.heappop(max_heap) # 1 +# Pop the top element from the heap +# The elements are popped in descending order +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 # Get the heap size size: int = len(max_heap) @@ -33,30 +33,31 @@ size: int = len(max_heap) # Check whether the heap is empty is_empty: bool = not max_heap -# Build a heap from a list +# Build a heap from an input list +# The time complexity is O(n), not O(nlogn) min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) ``` ```cpp title="heap.cpp" -/* Initialize a heap */ +/* Initialize the heap */ // Initialize a min heap priority_queue, greater> minHeap; // Initialize a max heap priority_queue, less> maxHeap; -/* Insert elements into the heap */ +/* Push an element onto the heap */ maxHeap.push(1); maxHeap.push(3); maxHeap.push(2); maxHeap.push(5); maxHeap.push(4); -/* Access the root element */ +/* Get the top element of the heap */ int peek = maxHeap.top(); // 5 -/* Remove root elements */ -// Removed elements form a descending sequence +/* Pop the top element from the heap */ +// The elements are popped in descending order maxHeap.pop(); // 5 maxHeap.pop(); // 4 maxHeap.pop(); // 3 @@ -69,30 +70,31 @@ int size = maxHeap.size(); /* Check whether the heap is empty */ bool isEmpty = maxHeap.empty(); -/* Build a heap from a list */ +/* Build a heap from an input list */ +// The time complexity is O(n), not O(nlogn) vector input{1, 3, 2, 5, 4}; minHeap = priority_queue, greater>(input.begin(), input.end()); ``` ```java title="heap.java" -/* Initialize a heap */ +/* Initialize heaps */ // Initialize a min heap Queue minHeap = new PriorityQueue<>(); -// Initialize a max heap by changing the Comparator with a lambda expression +// Initialize a max heap by supplying a lambda expression as the Comparator Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); -/* Insert elements into the heap */ +/* Push an element onto the heap */ maxHeap.offer(1); maxHeap.offer(3); maxHeap.offer(2); maxHeap.offer(5); maxHeap.offer(4); -/* Access the root element */ +/* Get the top element of the heap */ int peek = maxHeap.peek(); // 5 -/* Remove root elements */ -// Removed elements form a descending sequence +/* Pop the top element from the heap */ +// The elements are popped in descending order peek = maxHeap.poll(); // 5 peek = maxHeap.poll(); // 4 peek = maxHeap.poll(); // 3 @@ -105,34 +107,35 @@ int size = maxHeap.size(); /* Check whether the heap is empty */ boolean isEmpty = maxHeap.isEmpty(); -/* Build a heap from a list */ +/* Build a heap from an input list */ +// The time complexity is O(n), not O(nlogn) minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); ``` ```csharp title="heap.cs" -/* Initialize a heap */ +/* Initialize heaps */ // Initialize a min heap PriorityQueue minHeap = new(); -// Initialize a max heap by changing the Comparer with a lambda expression +// Initialize a max heap (use a lambda expression to customize the Comparer) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); -/* Insert elements into the heap */ +/* Push an element onto the heap */ maxHeap.Enqueue(1, 1); maxHeap.Enqueue(3, 3); maxHeap.Enqueue(2, 2); maxHeap.Enqueue(5, 5); maxHeap.Enqueue(4, 4); -/* Access the root element */ -int peek = maxHeap.Peek();//5 +/* Get the top element of the heap */ +int peek = maxHeap.Peek(); // 5 -/* Remove root elements */ -// Removed elements form a descending sequence -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +/* Pop the top element from the heap */ +// The elements are popped in descending order +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 /* Get the heap size */ int size = maxHeap.Count; @@ -140,7 +143,8 @@ int size = maxHeap.Count; /* Check whether the heap is empty */ bool isEmpty = maxHeap.Count == 0; -/* Build a heap from a list */ +/* Build a heap from an input list */ +// The time complexity is O(n), not O(nlogn) minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); ``` @@ -149,94 +153,96 @@ minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); // Implementing heap.Interface also requires implementing sort.Interface type intHeap []any -// Push implements the heap.Interface method for inserting an element +// Push is a heap.Interface function that pushes an element onto the heap func (h *intHeap) Push(x any) { // Push and Pop use pointer receivers - // because they change the slice length as well as its contents. + // because they modify the slice length as well as its contents. *h = append(*h, x.(int)) } -// Pop implements the heap.Interface method used to remove the root element +// Pop is a heap.Interface function that pops the top element from the heap func (h *intHeap) Pop() any { - // The element to remove has been placed at the end + // The element to remove is stored at the end last := (*h)[len(*h)-1] *h = (*h)[:len(*h)-1] return last } -// Len implements a sort.Interface method +// Len implements the sort.Interface length method func (h *intHeap) Len() int { return len(*h) } -// Less implements a sort.Interface method +// Less implements the sort.Interface comparison method func (h *intHeap) Less(i, j int) bool { - // For a min heap, change this to a less-than comparison + // For a min heap, change the comparison to less than return (*h)[i].(int) > (*h)[j].(int) } -// Swap implements a sort.Interface method +// Swap implements the sort.Interface swap method func (h *intHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } -// Top returns the root element +// Top returns the top element of the heap func (h *intHeap) Top() any { return (*h)[0] } -/* Driver Code */ func TestHeap(t *testing.T) { - /* Initialize a heap */ + /* Initialize the heap */ // Initialize a max heap maxHeap := &intHeap{} heap.Init(maxHeap) - /* Insert elements into the heap */ - // Call the heap.Interface methods to add elements + /* Push an element onto the heap */ + // Call a heap.Interface function to add an element heap.Push(maxHeap, 1) heap.Push(maxHeap, 3) heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) - /* Access the root element */ + /* Get the top element of the heap */ top := maxHeap.Top() - fmt.Printf("The root element is %d\n", top) + fmt.Printf("Top element of the heap: %d\n", top) - /* Remove root elements */ - // Call the heap.Interface methods to remove elements - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 + /* Pop the top element from the heap */ + // Call a heap.Interface function to remove an element + fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 5 + fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 4 + fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 3 + fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 2 + fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 1 /* Get the heap size */ size := len(*maxHeap) - fmt.Printf("The heap contains %d elements\n", size) + fmt.Printf("Number of elements in the heap: %d\n", size) /* Check whether the heap is empty */ isEmpty := len(*maxHeap) == 0 - fmt.Printf("Is the heap empty: %t\n", isEmpty) + fmt.Printf("Is the heap empty? %t\n", isEmpty) } ``` ```swift title="heap.swift" -/* Initialize a heap */ -// Swift's Heap type supports both minimum and maximum operations and requires swift-collections +import HeapModule + +/* Initialize the heap */ +// Swift's Heap type supports both max heap and min heap operations and requires the swift-collections package var heap = Heap() -/* Insert elements into the heap */ +/* Push an element onto the heap */ heap.insert(1) heap.insert(3) heap.insert(2) heap.insert(5) heap.insert(4) -/* Access the root element */ -var peek = heap.max()! +/* Get the maximum element of the heap */ +var peek = heap.max() -/* Remove root elements */ +/* Remove the maximum element from the heap */ peek = heap.removeMax() // 5 peek = heap.removeMax() // 4 peek = heap.removeMax() // 3 @@ -249,7 +255,8 @@ let size = heap.count /* Check whether the heap is empty */ let isEmpty = heap.isEmpty -/* Build a heap from a list */ +/* Build a heap from an input list */ +// The time complexity is O(n), not O(nlogn) let heap2 = Heap([1, 3, 2, 5, 4]) ``` @@ -266,32 +273,33 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +use std::{cmp::Reverse, collections::BinaryHeap}; -/* Initialize a heap */ +/* Initialize the heap */ // Initialize a min heap -let mut min_heap = BinaryHeap::>::new(); +// Rust's BinaryHeap is a max heap; wrap elements in Reverse to create a min heap +#[allow(unused_assignments)] +let mut min_heap = BinaryHeap::new(); // Initialize a max heap let mut max_heap = BinaryHeap::new(); -/* Insert elements into the heap */ +/* Push an element onto the heap */ max_heap.push(1); max_heap.push(3); max_heap.push(2); max_heap.push(5); max_heap.push(4); -/* Access the root element */ -let peek = max_heap.peek().unwrap(); // 5 +/* Get the top element of the heap */ +let peek = max_heap.peek().unwrap(); // 5 -/* Remove root elements */ -// Removed elements form a descending sequence -let peek = max_heap.pop().unwrap(); // 5 -let peek = max_heap.pop().unwrap(); // 4 -let peek = max_heap.pop().unwrap(); // 3 -let peek = max_heap.pop().unwrap(); // 2 -let peek = max_heap.pop().unwrap(); // 1 +/* Pop the top element from the heap */ +// The elements are popped in descending order +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 /* Get the heap size */ let size = max_heap.len(); @@ -299,8 +307,9 @@ let size = max_heap.len(); /* Check whether the heap is empty */ let is_empty = max_heap.is_empty(); -/* Build a heap from a list */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +/* Build a heap from an input list */ +// The time complexity is O(n), not O(nlogn) +min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); ``` ```c title="heap.c" @@ -308,24 +317,24 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse ``` ```kotlin title="heap.kt" -/* Initialize a heap */ +/* Initialize heaps */ // Initialize a min heap var minHeap = PriorityQueue() -// Initialize a max heap by changing the Comparator with a lambda expression +// Initialize a max heap by supplying a lambda expression as the Comparator val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } -/* Insert elements into the heap */ +/* Push an element onto the heap */ maxHeap.offer(1) maxHeap.offer(3) maxHeap.offer(2) maxHeap.offer(5) maxHeap.offer(4) -/* Access the root element */ +/* Get the top element of the heap */ var peek = maxHeap.peek() // 5 -/* Remove root elements */ -// Removed elements form a descending sequence +/* Pop the top element from the heap */ +// The elements are popped in descending order peek = maxHeap.poll() // 5 peek = maxHeap.poll() // 4 peek = maxHeap.poll() // 3 @@ -338,8 +347,9 @@ val size = maxHeap.size /* Check whether the heap is empty */ val isEmpty = maxHeap.isEmpty() -/* Build a heap from a list */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +/* Build a heap from an input list */ +// The time complexity is O(n), not O(nlogn) +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` ```ruby title="heap.rb" @@ -347,4 +357,4 @@ minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` -https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20min%20heap%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20Initialize%20a%20max%20heap%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%27s%20heapq%20module%20implements%20a%20min%20heap%20by%20default%0A%20%20%20%20%23%20Negate%20elements%20before%20insertion%20to%20reverse%20their%20order%20and%20implement%20a%20max%20heap%0A%20%20%20%20%23%20Here%2C%20flag%20%3D%201%20gives%20a%20min%20heap%20and%20flag%20%3D%20-1%20gives%20a%20max%20heap%0A%20%20%20%20%0A%20%20%20%20%23%20Insert%20elements%20into%20the%20heap%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20Access%20the%20root%20element%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20Remove%20root%20elements%0A%20%20%20%20%23%20Removed%20elements%20form%20a%20descending%20sequence%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20Get%20the%20heap%20size%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20Check%20whether%20the%20heap%20is%20empty%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20Build%20a%20heap%20from%20a%20list%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20min%20heap%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20Initialize%20a%20max%20heap%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%27s%20heapq%20module%20implements%20a%20min%20heap%20by%20default%0A%20%20%20%20%23%20Negate%20elements%20before%20insertion%20to%20reverse%20their%20order%20and%20implement%20a%20max%20heap%0A%20%20%20%20%23%20Here%2C%20flag%20%3D%201%20gives%20a%20min%20heap%20and%20flag%20%3D%20-1%20gives%20a%20max%20heap%0A%20%20%20%20%0A%20%20%20%20%23%20Insert%20elements%20into%20the%20heap%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20Access%20the%20root%20element%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20Remove%20root%20elements%0A%20%20%20%20%23%20Removed%20elements%20form%20a%20descending%20sequence%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20Get%20the%20heap%20size%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20Check%20whether%20the%20heap%20is%20empty%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20Build%20a%20heap%20from%20a%20list%0A%20%20%20%20%23%20The%20time%20complexity%20is%20O%28n%29%2C%20not%20O%28nlogn%29%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/snippets/chapter_stack_and_queue/deque.md b/en/codes/snippets/chapter_stack_and_queue/deque.md index bed0f7ba4..01ded2e6e 100644 --- a/en/codes/snippets/chapter_stack_and_queue/deque.md +++ b/en/codes/snippets/chapter_stack_and_queue/deque.md @@ -2,23 +2,23 @@ ```python title="deque.py" from collections import deque -# Initialize a deque +# Initialize the deque deq: deque[int] = deque() # Enqueue elements -deq.append(2) # Add at the rear +deq.append(2) # Add to the rear deq.append(5) deq.append(4) -deq.appendleft(3) # Add at the front +deq.appendleft(3) # Add to the front deq.appendleft(1) -# Access elements +# Access an element front: int = deq[0] # Front element rear: int = deq[-1] # Rear element -# Dequeue elements -pop_front: int = deq.popleft() # Remove the front element -pop_rear: int = deq.pop() # Remove the rear element +# Dequeue an element +pop_front: int = deq.popleft() # Dequeue the front element +pop_rear: int = deq.pop() # Dequeue the rear element # Get the deque size size: int = len(deq) @@ -28,23 +28,23 @@ is_empty: bool = len(deq) == 0 ``` ```cpp title="deque.cpp" -/* Initialize a deque */ +/* Initialize the deque */ deque deque; /* Enqueue elements */ -deque.push_back(2); // Add at the rear +deque.push_back(2); // Add to the rear deque.push_back(5); deque.push_back(4); -deque.push_front(3); // Add at the front +deque.push_front(3); // Add to the front deque.push_front(1); -/* Access elements */ +/* Access an element */ int front = deque.front(); // Front element -int back = deque.back(); // Rear element +int back = deque.back(); // Rear element -/* Dequeue elements */ -deque.pop_front(); // Remove the front element -deque.pop_back(); // Remove the rear element +/* Dequeue an element */ +deque.pop_front(); // Dequeue the front element +deque.pop_back(); // Dequeue the rear element /* Get the deque size */ int size = deque.size(); @@ -54,23 +54,23 @@ bool empty = deque.empty(); ``` ```java title="deque.java" -/* Initialize a deque */ +/* Initialize the deque */ Deque deque = new LinkedList<>(); /* Enqueue elements */ -deque.offerLast(2); // Add at the rear +deque.offerLast(2); // Add to the rear deque.offerLast(5); deque.offerLast(4); -deque.offerFirst(3); // Add at the front +deque.offerFirst(3); // Add to the front deque.offerFirst(1); -/* Access elements */ -int peekFirst = deque.peekFirst(); // Front element -int peekLast = deque.peekLast(); // Rear element +/* Access an element */ +int peekFirst = deque.peekFirst(); // Front element +int peekLast = deque.peekLast(); // Rear element -/* Dequeue elements */ -int popFirst = deque.pollFirst(); // Remove the front element -int popLast = deque.pollLast(); // Remove the rear element +/* Dequeue an element */ +int popFirst = deque.pollFirst(); // Dequeue the front element +int popLast = deque.pollLast(); // Dequeue the rear element /* Get the deque size */ int size = deque.size(); @@ -80,24 +80,24 @@ boolean isEmpty = deque.isEmpty(); ``` ```csharp title="deque.cs" -/* Initialize a deque */ -// In C#, use a LinkedList as a deque +/* Initialize the deque */ +// In C#, use the linked list LinkedList as a deque LinkedList deque = new(); /* Enqueue elements */ -deque.AddLast(2); // Add at the rear +deque.AddLast(2); // Add to the rear deque.AddLast(5); deque.AddLast(4); -deque.AddFirst(3); // Add at the front +deque.AddFirst(3); // Add to the front deque.AddFirst(1); -/* Access elements */ -int peekFirst = deque.First.Value; // Front element -int peekLast = deque.Last.Value; // Rear element +/* Access an element */ +int? peekFirst = deque.First?.Value; // Front element +int? peekLast = deque.Last?.Value; // Rear element -/* Dequeue elements */ -deque.RemoveFirst(); // Remove the front element -deque.RemoveLast(); // Remove the rear element +/* Dequeue an element */ +deque.RemoveFirst(); // Dequeue the front element +deque.RemoveLast(); // Dequeue the rear element /* Get the deque size */ int size = deque.Count; @@ -107,24 +107,24 @@ bool isEmpty = deque.Count == 0; ``` ```go title="deque_test.go" -/* Initialize a deque */ -// In Go, use a list as a deque +/* Initialize the deque */ +// In Go, list can be used as a deque deque := list.New() /* Enqueue elements */ -deque.PushBack(2) // Add at the rear +deque.PushBack(2) // Add to the rear deque.PushBack(5) deque.PushBack(4) -deque.PushFront(3) // Add at the front +deque.PushFront(3) // Add to the front deque.PushFront(1) -/* Access elements */ +/* Access an element */ front := deque.Front() // Front element -rear := deque.Back() // Rear element +rear := deque.Back() // Rear element -/* Dequeue elements */ -deque.Remove(front) // Remove the front element -deque.Remove(rear) // Remove the rear element +/* Dequeue an element */ +deque.Remove(front) // Dequeue the front element +deque.Remove(rear) // Dequeue the rear element /* Get the deque size */ size := deque.Len() @@ -134,25 +134,25 @@ isEmpty := deque.Len() == 0 ``` ```swift title="deque.swift" -/* Initialize a deque */ -// Swift has no built-in deque class; use an Array as a deque +/* Initialize the deque */ +// The Swift standard library has no built-in deque class; Array can be used as a deque var deque: [Int] = [] /* Enqueue elements */ -deque.append(2) // Add at the rear +deque.append(2) // Add to the rear deque.append(5) deque.append(4) -deque.insert(3, at: 0) // Add at the front +deque.insert(3, at: 0) // Add to the front deque.insert(1, at: 0) -/* Access elements */ +/* Access an element */ let peekFirst = deque.first! // Front element let peekLast = deque.last! // Rear element -/* Dequeue elements */ -// When using an Array, popFirst takes O(n) time -let popFirst = deque.removeFirst() // Remove the front element -let popLast = deque.removeLast() // Remove the rear element +/* Dequeue an element */ +// When using Array to simulate a deque, removeFirst has O(n) complexity +let popFirst = deque.removeFirst() // Dequeue the front element +let popLast = deque.removeLast() // Dequeue the rear element /* Get the deque size */ let size = deque.count @@ -162,24 +162,24 @@ let isEmpty = deque.isEmpty ``` ```javascript title="deque.js" -/* Initialize a deque */ -// JavaScript has no built-in deque; use an Array instead +/* Initialize the deque */ +// JavaScript has no built-in deque; use an Array as a deque const deque = []; /* Enqueue elements */ deque.push(2); deque.push(5); deque.push(4); -// Note that this is an array, so unshift() takes O(n) time +// Note: because this uses an array, unshift() has O(n) time complexity deque.unshift(3); deque.unshift(1); -/* Access elements */ +/* Access an element */ const peekFirst = deque[0]; const peekLast = deque[deque.length - 1]; -/* Dequeue elements */ -// Note that this is an array, so shift() takes O(n) time +/* Dequeue an element */ +// Note: because this uses an array, shift() has O(n) time complexity const popFront = deque.shift(); const popBack = deque.pop(); @@ -191,24 +191,24 @@ const isEmpty = size === 0; ``` ```typescript title="deque.ts" -/* Initialize a deque */ -// TypeScript has no built-in deque; use an Array instead +/* Initialize the deque */ +// TypeScript has no built-in deque; use an Array as a deque instead const deque: number[] = []; /* Enqueue elements */ deque.push(2); deque.push(5); deque.push(4); -// Note that this is an array, so unshift() takes O(n) time +// Note: because this uses an array, unshift() has O(n) time complexity deque.unshift(3); deque.unshift(1); -/* Access elements */ +/* Access an element */ const peekFirst: number = deque[0]; const peekLast: number = deque[deque.length - 1]; -/* Dequeue elements */ -// Note that this is an array, so shift() takes O(n) time +/* Dequeue an element */ +// Note: because this uses an array, shift() has O(n) time complexity const popFront: number = deque.shift() as number; const popBack: number = deque.pop() as number; @@ -220,59 +220,55 @@ const isEmpty: boolean = size === 0; ``` ```dart title="deque.dart" -/* Initialize a deque */ +/* Initialize the deque */ // In Dart, Queue is defined as a deque -Queue deque = Queue(); +final Queue deque = Queue(); /* Enqueue elements */ -deque.addLast(2); // Add at the rear +deque.addLast(2); // Add to the rear deque.addLast(5); deque.addLast(4); -deque.addFirst(3); // Add at the front +deque.addFirst(3); // Add to the front deque.addFirst(1); -/* Access elements */ -int peekFirst = deque.first; // Front element -int peekLast = deque.last; // Rear element +/* Access an element */ +final int peekFirst = deque.first; // Front element +final int peekLast = deque.last; // Rear element -/* Dequeue elements */ -int popFirst = deque.removeFirst(); // Remove the front element -int popLast = deque.removeLast(); // Remove the rear element +/* Dequeue an element */ +final int popFirst = deque.removeFirst(); // Dequeue the front element +final int popLast = deque.removeLast(); // Dequeue the rear element /* Get the deque size */ -int size = deque.length; +final int size = deque.length; /* Check whether the deque is empty */ -bool isEmpty = deque.isEmpty; +final bool isEmpty = deque.isEmpty; ``` ```rust title="deque.rs" -/* Initialize a deque */ -let mut deque: VecDeque = VecDeque::new(); +// Initialize the deque +let mut deque: VecDeque = VecDeque::new(); /* Enqueue elements */ -deque.push_back(2); // Add at the rear +deque.push_back(2); // Add to the rear deque.push_back(5); deque.push_back(4); -deque.push_front(3); // Add at the front +deque.push_front(3); // Add to the front deque.push_front(1); -/* Access elements */ -if let Some(front) = deque.front() { // Front element -} -if let Some(rear) = deque.back() { // Rear element -} +// Access an element +let peek_first = deque.front().unwrap(); // Front element +let peek_last = deque.back().unwrap(); // Rear element -/* Dequeue elements */ -if let Some(pop_front) = deque.pop_front() { // Remove the front element -} -if let Some(pop_rear) = deque.pop_back() { // Remove the rear element -} +// Dequeue an element +let pop_first = deque.pop_front().unwrap(); // Dequeue the front element +let pop_last = deque.pop_back().unwrap(); // Dequeue the rear element -/* Get the deque size */ +// Get the deque size let size = deque.len(); -/* Check whether the deque is empty */ +// Check whether the deque is empty let is_empty = deque.is_empty(); ``` @@ -281,23 +277,23 @@ let is_empty = deque.is_empty(); ``` ```kotlin title="deque.kt" -/* Initialize a deque */ +/* Initialize the deque */ val deque = LinkedList() /* Enqueue elements */ -deque.offerLast(2) // Add at the rear +deque.offerLast(2) // Add to the rear deque.offerLast(5) deque.offerLast(4) -deque.offerFirst(3) // Add at the front +deque.offerFirst(3) // Add to the front deque.offerFirst(1) -/* Access elements */ +/* Access an element */ val peekFirst = deque.peekFirst() // Front element -val peekLast = deque.peekLast() // Rear element +val peekLast = deque.peekLast() // Rear element -/* Dequeue elements */ -val popFirst = deque.pollFirst() // Remove the front element -val popLast = deque.pollLast() // Remove the rear element +/* Dequeue an element */ +val popFirst = deque.pollFirst() // Dequeue the front element +val popLast = deque.pollLast() // Dequeue the rear element /* Get the deque size */ val size = deque.size @@ -307,24 +303,24 @@ val isEmpty = deque.isEmpty() ``` ```ruby title="deque.rb" -# Initialize a deque -# Ruby has no built-in deque; use an Array instead +# Initialize the deque +# Ruby has no built-in deque class; use an Array as a deque deque = [] # Enqueue elements deque << 2 deque << 5 deque << 4 -# Note that this is an array, so Array#unshift takes O(n) time +# Note that Array#unshift has O(n) time complexity because the underlying structure is an array deque.unshift(3) deque.unshift(1) -# Access elements +# Access an element peek_first = deque.first peek_last = deque.last -# Dequeue elements -# Note that this is an array, so Array#shift takes O(n) time +# Dequeue an element +# Note that Array#shift has O(n) time complexity because the underlying structure is an array pop_front = deque.shift pop_back = deque.pop diff --git a/en/codes/snippets/chapter_stack_and_queue/queue.md b/en/codes/snippets/chapter_stack_and_queue/queue.md index 9121a06bc..ea6659bf5 100644 --- a/en/codes/snippets/chapter_stack_and_queue/queue.md +++ b/en/codes/snippets/chapter_stack_and_queue/queue.md @@ -2,9 +2,9 @@ ```python title="queue.py" from collections import deque -# Initialize a queue -# In Python, we usually use the deque class as a queue -# Although queue.Queue() is a dedicated queue class, it is less convenient and is not recommended here +# Initialize the queue +# In Python, we generally use the deque class as a queue +# Although queue.Queue() is a dedicated queue class, it is less convenient to use and is therefore not recommended que: deque[int] = deque() # Enqueue elements @@ -28,7 +28,7 @@ is_empty: bool = len(que) == 0 ``` ```cpp title="queue.cpp" -/* Initialize a queue */ +/* Initialize the queue */ queue queue; /* Enqueue elements */ @@ -52,7 +52,7 @@ bool empty = queue.empty(); ``` ```java title="queue.java" -/* Initialize a queue */ +/* Initialize the queue */ Queue queue = new LinkedList<>(); /* Enqueue elements */ @@ -76,7 +76,7 @@ boolean isEmpty = queue.isEmpty(); ``` ```csharp title="queue.cs" -/* Initialize a queue */ +/* Initialize the queue */ Queue queue = new(); /* Enqueue elements */ @@ -100,8 +100,8 @@ bool isEmpty = queue.Count == 0; ``` ```go title="queue_test.go" -/* Initialize a queue */ -// In Go, use a list as a queue +/* Initialize the queue */ +// In Go, use list as a queue queue := list.New() /* Enqueue elements */ @@ -126,8 +126,8 @@ isEmpty := queue.Len() == 0 ``` ```swift title="queue.swift" -/* Initialize a queue */ -// Swift has no built-in queue class; use an Array as a queue +/* Initialize the queue */ +// The Swift standard library has no built-in queue class; Array can be used as a queue var queue: [Int] = [] /* Enqueue elements */ @@ -141,7 +141,7 @@ queue.append(4) let peek = queue.first! /* Dequeue an element */ -// Because this is an array, removeFirst takes O(n) time +// When using Array as a queue, removeFirst has O(n) time complexity let pop = queue.removeFirst() /* Get the queue size */ @@ -152,8 +152,8 @@ let isEmpty = queue.isEmpty ``` ```javascript title="queue.js" -/* Initialize a queue */ -// JavaScript has no built-in queue; use an Array as a queue +/* Initialize the queue */ +// JavaScript has no built-in queue; an Array can be used as a queue const queue = []; /* Enqueue elements */ @@ -167,19 +167,19 @@ queue.push(4); const peek = queue[0]; /* Dequeue an element */ -// The underlying structure is an array, so shift() takes O(n) time +// The underlying structure is an array, so shift() has O(n) time complexity const pop = queue.shift(); /* Get the queue size */ const size = queue.length; /* Check whether the queue is empty */ -const empty = queue.length === 0; +const isEmpty = queue.length === 0; ``` ```typescript title="queue.ts" -/* Initialize a queue */ -// TypeScript has no built-in queue; use an Array as a queue +/* Initialize the queue */ +// TypeScript has no built-in queue; an Array can be used as a queue const queue: number[] = []; /* Enqueue elements */ @@ -193,20 +193,20 @@ queue.push(4); const peek = queue[0]; /* Dequeue an element */ -// The underlying structure is an array, so shift() takes O(n) time +// The underlying structure is an array, so shift() has O(n) time complexity const pop = queue.shift(); /* Get the queue size */ const size = queue.length; /* Check whether the queue is empty */ -const empty = queue.length === 0; +const isEmpty = queue.length === 0; ``` ```dart title="queue.dart" -/* Initialize a queue */ -// In Dart, Queue is a deque and can also be used as a queue -Queue queue = Queue(); +/* Initialize the queue */ +// In Dart, the deque class Queue is commonly used as a queue +final Queue queue = Queue(); /* Enqueue elements */ queue.add(1); @@ -216,43 +216,41 @@ queue.add(5); queue.add(4); /* Access the front element */ -int peek = queue.first; +final int peek = queue.first; /* Dequeue an element */ -int pop = queue.removeFirst(); +final int pop = queue.removeFirst(); /* Get the queue size */ -int size = queue.length; +final int size = queue.length; /* Check whether the queue is empty */ -bool isEmpty = queue.isEmpty; +final bool isEmpty = queue.isEmpty; ``` ```rust title="queue.rs" -/* Initialize a deque */ -// In Rust, use a deque as an ordinary queue -let mut deque: VecDeque = VecDeque::new(); +// Initialize the queue +// In Rust, the deque VecDeque is commonly used as a queue +let mut queue: VecDeque = VecDeque::new(); -/* Enqueue elements */ -deque.push_back(1); -deque.push_back(3); -deque.push_back(2); -deque.push_back(5); -deque.push_back(4); +// Enqueue elements +queue.push_back(1); +queue.push_back(3); +queue.push_back(2); +queue.push_back(5); +queue.push_back(4); -/* Access the front element */ -if let Some(front) = deque.front() { -} +// Access the front element +let peek = queue.front().unwrap(); -/* Dequeue an element */ -if let Some(pop) = deque.pop_front() { -} +// Dequeue an element +let pop = queue.pop_front().unwrap(); -/* Get the queue size */ -let size = deque.len(); +// Get the queue size +let size = queue.len(); -/* Check whether the queue is empty */ -let is_empty = deque.is_empty(); +// Check whether the queue is empty +let is_empty = queue.is_empty(); ``` ```c title="queue.c" @@ -260,7 +258,7 @@ let is_empty = deque.is_empty(); ``` ```kotlin title="queue.kt" -/* Initialize a queue */ +/* Initialize the queue */ val queue = LinkedList() /* Enqueue elements */ @@ -284,8 +282,8 @@ val isEmpty = queue.isEmpty() ``` ```ruby title="queue.rb" -# Initialize a queue -# Ruby's built-in Thread::Queue has no peek or traversal methods; use an Array as a queue +# Initialize the queue +# The built-in Ruby queue (Thread::Queue) has no peek or traversal methods; use an Array as a queue queue = [] # Enqueue elements @@ -295,11 +293,11 @@ queue.push(2) queue.push(5) queue.push(4) -# Access the front element of the queue +# Access a queue element peek = queue.first # Dequeue an element -# Note that this is an array, so Array#shift takes O(n) time +# Note that Array#shift has O(n) time complexity because the underlying structure is an array pop = queue.shift # Get the queue size diff --git a/en/codes/snippets/chapter_stack_and_queue/stack.md b/en/codes/snippets/chapter_stack_and_queue/stack.md index 32d607cb1..5dc602888 100644 --- a/en/codes/snippets/chapter_stack_and_queue/stack.md +++ b/en/codes/snippets/chapter_stack_and_queue/stack.md @@ -1,10 +1,10 @@ ```python title="stack.py" -# Initialize a stack -# Python has no built-in stack class; use a list as a stack +# Initialize the stack +# Python has no built-in stack class; a list can be used as a stack stack: list[int] = [] -# Push elements +# Push elements onto the stack stack.append(1) stack.append(3) stack.append(2) @@ -14,21 +14,21 @@ stack.append(4) # Access the top element peek: int = stack[-1] -# Pop an element +# Pop an element from the stack pop: int = stack.pop() # Get the stack size size: int = len(stack) -# Check whether the stack is empty +# Check whether it is empty is_empty: bool = len(stack) == 0 ``` ```cpp title="stack.cpp" -/* Initialize a stack */ +/* Initialize the stack */ stack stack; -/* Push elements */ +/* Push elements onto the stack */ stack.push(1); stack.push(3); stack.push(2); @@ -38,21 +38,21 @@ stack.push(4); /* Access the top element */ int top = stack.top(); -/* Pop an element */ +/* Pop an element from the stack */ stack.pop(); // No return value /* Get the stack size */ int size = stack.size(); -/* Check whether the stack is empty */ +/* Check whether it is empty */ bool empty = stack.empty(); ``` ```java title="stack.java" -/* Initialize a stack */ +/* Initialize the stack */ Stack stack = new Stack<>(); -/* Push elements */ +/* Push elements onto the stack */ stack.push(1); stack.push(3); stack.push(2); @@ -62,21 +62,21 @@ stack.push(4); /* Access the top element */ int peek = stack.peek(); -/* Pop an element */ +/* Pop an element from the stack */ int pop = stack.pop(); /* Get the stack size */ int size = stack.size(); -/* Check whether the stack is empty */ +/* Check whether it is empty */ boolean isEmpty = stack.isEmpty(); ``` ```csharp title="stack.cs" -/* Initialize a stack */ +/* Initialize the stack */ Stack stack = new(); -/* Push elements */ +/* Push elements onto the stack */ stack.Push(1); stack.Push(3); stack.Push(2); @@ -86,22 +86,22 @@ stack.Push(4); /* Access the top element */ int peek = stack.Peek(); -/* Pop an element */ +/* Pop an element from the stack */ int pop = stack.Pop(); /* Get the stack size */ int size = stack.Count; -/* Check whether the stack is empty */ +/* Check whether it is empty */ bool isEmpty = stack.Count == 0; ``` ```go title="stack_test.go" -/* Initialize a stack */ -// In Go, a slice is recommended for use as a stack +/* Initialize the stack */ +// In Go, a slice is the recommended way to implement a stack var stack []int -/* Push elements */ +/* Push elements onto the stack */ stack = append(stack, 1) stack = append(stack, 3) stack = append(stack, 2) @@ -111,23 +111,23 @@ stack = append(stack, 4) /* Access the top element */ peek := stack[len(stack)-1] -/* Pop an element */ +/* Pop an element from the stack */ pop := stack[len(stack)-1] stack = stack[:len(stack)-1] /* Get the stack size */ size := len(stack) -/* Check whether the stack is empty */ +/* Check whether it is empty */ isEmpty := len(stack) == 0 ``` ```swift title="stack.swift" -/* Initialize a stack */ -// Swift has no built-in stack class; use an Array as a stack +/* Initialize the stack */ +// The Swift standard library has no built-in stack class; Array can be used as a stack var stack: [Int] = [] -/* Push elements */ +/* Push elements onto the stack */ stack.append(1) stack.append(3) stack.append(2) @@ -137,47 +137,22 @@ stack.append(4) /* Access the top element */ let peek = stack.last! -/* Pop an element */ +/* Pop an element from the stack */ let pop = stack.removeLast() /* Get the stack size */ let size = stack.count -/* Check whether the stack is empty */ +/* Check whether it is empty */ let isEmpty = stack.isEmpty ``` ```javascript title="stack.js" -/* Initialize a stack */ -// JavaScript has no built-in stack class; use an Array as a stack +/* Initialize the stack */ +// JavaScript has no built-in stack class; an Array can be used as a stack const stack = []; -/* Push elements */ -stack.push(1); -stack.push(3); -stack.push(2); -stack.push(5); -stack.push(4); - -/* Access the top element */ -const peek = stack[stack.length-1]; - -/* Pop an element */ -const pop = stack.pop(); - -/* Get the stack size */ -const size = stack.length; - -/* Check whether the stack is empty */ -const is_empty = stack.length === 0; -``` - -```typescript title="stack.ts" -/* Initialize a stack */ -// TypeScript has no built-in stack class; use an Array as a stack -const stack: number[] = []; - -/* Push elements */ +/* Push elements onto the stack */ stack.push(1); stack.push(3); stack.push(2); @@ -187,47 +162,22 @@ stack.push(4); /* Access the top element */ const peek = stack[stack.length - 1]; -/* Pop an element */ +/* Pop an element from the stack */ const pop = stack.pop(); /* Get the stack size */ const size = stack.length; -/* Check whether the stack is empty */ -const is_empty = stack.length === 0; +/* Check whether it is empty */ +const isEmpty = stack.length === 0; ``` -```dart title="stack.dart" -/* Initialize a stack */ -// Dart has no built-in stack class; use a List as a stack -List stack = []; +```typescript title="stack.ts" +/* Initialize the stack */ +// TypeScript has no built-in stack class; an Array can be used as a stack +const stack: number[] = []; -/* Push elements */ -stack.add(1); -stack.add(3); -stack.add(2); -stack.add(5); -stack.add(4); - -/* Access the top element */ -int peek = stack.last; - -/* Pop an element */ -int pop = stack.removeLast(); - -/* Get the stack size */ -int size = stack.length; - -/* Check whether the stack is empty */ -bool isEmpty = stack.isEmpty; -``` - -```rust title="stack.rs" -/* Initialize a stack */ -// Use a Vec as a stack -let mut stack: Vec = Vec::new(); - -/* Push elements */ +/* Push elements onto the stack */ stack.push(1); stack.push(3); stack.push(2); @@ -235,15 +185,65 @@ stack.push(5); stack.push(4); /* Access the top element */ -let top = stack.last().unwrap(); +const peek = stack[stack.length - 1]; -/* Pop an element */ -let pop = stack.pop().unwrap(); +/* Pop an element from the stack */ +const pop = stack.pop(); /* Get the stack size */ +const size = stack.length; + +/* Check whether it is empty */ +const isEmpty = stack.length === 0; +``` + +```dart title="stack.dart" +/* Initialize the stack */ +// Dart has no built-in stack class; a List can be used as a stack +final List stack = []; + +/* Push elements onto the stack */ +stack.add(1); +stack.add(3); +stack.add(2); +stack.add(5); +stack.add(4); + +/* Access the top element */ +final int peek = stack.last; + +/* Pop an element from the stack */ +final int pop = stack.removeLast(); + +/* Get the stack size */ +final int size = stack.length; + +/* Check whether it is empty */ +final bool isEmpty = stack.isEmpty; +``` + +```rust title="stack.rs" +// Initialize the stack +// In Rust, Vec is the recommended type for implementing a stack +let mut stack: Vec = Vec::new(); + +// Push elements onto the stack +stack.push(1); +stack.push(3); +stack.push(2); +stack.push(5); +stack.push(4); + +// Access the top element +let peek = stack.last().unwrap(); + +// Pop an element from the stack +let pop = stack.pop().unwrap(); + +// Get the stack size let size = stack.len(); -/* Check whether the stack is empty */ +// Check whether the stack is empty let is_empty = stack.is_empty(); ``` @@ -252,10 +252,10 @@ let is_empty = stack.is_empty(); ``` ```kotlin title="stack.kt" -/* Initialize a stack */ +/* Initialize the stack */ val stack = Stack() -/* Push elements */ +/* Push elements onto the stack */ stack.push(1) stack.push(3) stack.push(2) @@ -265,22 +265,22 @@ stack.push(4) /* Access the top element */ val peek = stack.peek() -/* Pop an element */ +/* Pop an element from the stack */ val pop = stack.pop() /* Get the stack size */ val size = stack.size -/* Check whether the stack is empty */ +/* Check whether it is empty */ val isEmpty = stack.isEmpty() ``` ```ruby title="stack.rb" -# Initialize a stack +# Initialize the stack # Ruby has no built-in stack class; use an Array as a stack stack = [] -# Push elements +# Push elements onto the stack stack << 1 stack << 3 stack << 2 @@ -290,13 +290,13 @@ stack << 4 # Access the top element peek = stack.last -# Pop an element +# Pop an element from the stack pop = stack.pop # Get the stack size size = stack.length -# Check whether the stack is empty +# Check whether it is empty is_empty = stack.empty? ``` diff --git a/en/codes/snippets/chapter_tree/binary_tree.md b/en/codes/snippets/chapter_tree/binary_tree.md index d67a11547..b67ae44d2 100644 --- a/en/codes/snippets/chapter_tree/binary_tree.md +++ b/en/codes/snippets/chapter_tree/binary_tree.md @@ -133,7 +133,6 @@ impl TreeNode { /* Binary tree node struct */ typedef struct TreeNode { int val; // Node value - int height; // Node height struct TreeNode *left; // Left child pointer struct TreeNode *right; // Right child pointer } TreeNode; @@ -144,7 +143,6 @@ TreeNode *newTreeNode(int val) { node = (TreeNode *)malloc(sizeof(TreeNode)); node->val = val; - node->height = 0; node->left = NULL; node->right = NULL; return node; @@ -174,14 +172,14 @@ end ```python title="binary_tree.py" -# Initialize a binary tree -# Initialize nodes +# Initialize the binary tree +# Initialize the nodes n1 = TreeNode(val=1) n2 = TreeNode(val=2) n3 = TreeNode(val=3) n4 = TreeNode(val=4) n5 = TreeNode(val=5) -# Connect nodes with references (pointers) +# Set up references (pointers) between the nodes n1.left = n2 n1.right = n3 n2.left = n4 @@ -189,14 +187,14 @@ n2.right = n5 ``` ```cpp title="binary_tree.cpp" -/* Initialize a binary tree */ -// Initialize nodes -TreeNode* n1 = new TreeNode(1); -TreeNode* n2 = new TreeNode(2); -TreeNode* n3 = new TreeNode(3); -TreeNode* n4 = new TreeNode(4); -TreeNode* n5 = new TreeNode(5); -// Connect nodes with references (pointers) +/* Initialize the binary tree */ +// Initialize the nodes +TreeNode *n1 = new TreeNode(1); +TreeNode *n2 = new TreeNode(2); +TreeNode *n3 = new TreeNode(3); +TreeNode *n4 = new TreeNode(4); +TreeNode *n5 = new TreeNode(5); +// Set up references (pointers) between the nodes n1->left = n2; n1->right = n3; n2->left = n4; @@ -204,13 +202,14 @@ n2->right = n5; ``` ```java title="binary_tree.java" -// Initialize nodes +/* Initialize the binary tree */ +// Initialize the nodes TreeNode n1 = new TreeNode(1); TreeNode n2 = new TreeNode(2); TreeNode n3 = new TreeNode(3); TreeNode n4 = new TreeNode(4); TreeNode n5 = new TreeNode(5); -// Connect nodes with references (pointers) +// Set up references (pointers) between the nodes n1.left = n2; n1.right = n3; n2.left = n4; @@ -218,14 +217,14 @@ n2.right = n5; ``` ```csharp title="binary_tree.cs" -/* Initialize a binary tree */ -// Initialize nodes +/* Initialize the binary tree */ +// Initialize the nodes TreeNode n1 = new(1); TreeNode n2 = new(2); TreeNode n3 = new(3); TreeNode n4 = new(4); TreeNode n5 = new(5); -// Connect nodes with references (pointers) +// Set up references (pointers) between the nodes n1.left = n2; n1.right = n3; n2.left = n4; @@ -233,14 +232,14 @@ n2.right = n5; ``` ```go title="binary_tree.go" -/* Initialize a binary tree */ -// Initialize nodes +/* Initialize the binary tree */ +// Initialize the nodes n1 := NewTreeNode(1) n2 := NewTreeNode(2) n3 := NewTreeNode(3) n4 := NewTreeNode(4) n5 := NewTreeNode(5) -// Connect nodes with references (pointers) +// Set up references (pointers) between the nodes n1.Left = n2 n1.Right = n3 n2.Left = n4 @@ -248,13 +247,14 @@ n2.Right = n5 ``` ```swift title="binary_tree.swift" -// Initialize nodes +/* Initialize the binary tree */ +// Initialize the nodes let n1 = TreeNode(x: 1) let n2 = TreeNode(x: 2) let n3 = TreeNode(x: 3) let n4 = TreeNode(x: 4) let n5 = TreeNode(x: 5) -// Connect nodes with references (pointers) +// Set up references (pointers) between the nodes n1.left = n2 n1.right = n3 n2.left = n4 @@ -262,14 +262,14 @@ n2.right = n5 ``` ```javascript title="binary_tree.js" -/* Initialize a binary tree */ -// Initialize nodes +/* Initialize the binary tree */ +// Initialize the nodes let n1 = new TreeNode(1), n2 = new TreeNode(2), n3 = new TreeNode(3), n4 = new TreeNode(4), n5 = new TreeNode(5); -// Connect nodes with references (pointers) +// Set up references (pointers) between the nodes n1.left = n2; n1.right = n3; n2.left = n4; @@ -277,14 +277,14 @@ n2.right = n5; ``` ```typescript title="binary_tree.ts" -/* Initialize a binary tree */ -// Initialize nodes +/* Initialize the binary tree */ +// Initialize the nodes let n1 = new TreeNode(1), n2 = new TreeNode(2), n3 = new TreeNode(3), n4 = new TreeNode(4), n5 = new TreeNode(5); -// Connect nodes with references (pointers) +// Set up references (pointers) between the nodes n1.left = n2; n1.right = n3; n2.left = n4; @@ -292,14 +292,14 @@ n2.right = n5; ``` ```dart title="binary_tree.dart" -/* Initialize a binary tree */ -// Initialize nodes -TreeNode n1 = new TreeNode(1); -TreeNode n2 = new TreeNode(2); -TreeNode n3 = new TreeNode(3); -TreeNode n4 = new TreeNode(4); -TreeNode n5 = new TreeNode(5); -// Connect nodes with references (pointers) +/* Initialize the binary tree */ +// Initialize the nodes +TreeNode n1 = TreeNode(1); +TreeNode n2 = TreeNode(2); +TreeNode n3 = TreeNode(3); +TreeNode n4 = TreeNode(4); +TreeNode n5 = TreeNode(5); +// Set up references (pointers) between the nodes n1.left = n2; n1.right = n3; n2.left = n4; @@ -307,28 +307,29 @@ n2.right = n5; ``` ```rust title="binary_tree.rs" -// Initialize nodes +/* Initialize the binary tree */ +// Initialize the nodes let n1 = TreeNode::new(1); let n2 = TreeNode::new(2); let n3 = TreeNode::new(3); let n4 = TreeNode::new(4); let n5 = TreeNode::new(5); -// Connect nodes with references (pointers) -n1.borrow_mut().left = Some(n2.clone()); -n1.borrow_mut().right = Some(n3); -n2.borrow_mut().left = Some(n4); -n2.borrow_mut().right = Some(n5); +// Set up references (pointers) between the nodes +n1.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().right = Some(Rc::clone(&n3)); +n2.borrow_mut().left = Some(Rc::clone(&n4)); +n2.borrow_mut().right = Some(Rc::clone(&n5)); ``` ```c title="binary_tree.c" -/* Initialize a binary tree */ -// Initialize nodes +/* Initialize the binary tree */ +// Initialize the nodes TreeNode *n1 = newTreeNode(1); TreeNode *n2 = newTreeNode(2); TreeNode *n3 = newTreeNode(3); TreeNode *n4 = newTreeNode(4); TreeNode *n5 = newTreeNode(5); -// Connect nodes with references (pointers) +// Set up references (pointers) between the nodes n1->left = n2; n1->right = n3; n2->left = n4; @@ -336,13 +337,14 @@ n2->right = n5; ``` ```kotlin title="binary_tree.kt" -// Initialize nodes +/* Initialize the binary tree */ +// Initialize the nodes val n1 = TreeNode(1) val n2 = TreeNode(2) val n3 = TreeNode(3) val n4 = TreeNode(4) val n5 = TreeNode(5) -// Connect nodes with references (pointers) +// Set up references (pointers) between the nodes n1.left = n2 n1.right = n3 n2.left = n4 @@ -350,14 +352,14 @@ n2.right = n5 ``` ```ruby title="binary_tree.rb" -# Initialize a binary tree -# Initialize nodes +# Initialize the binary tree +# Initialize the nodes n1 = TreeNode.new(1) n2 = TreeNode.new(2) n3 = TreeNode.new(3) n4 = TreeNode.new(4) n5 = TreeNode.new(5) -# Connect nodes with references (pointers) +# Set up references (pointers) between the nodes n1.left = n2 n1.right = n3 n2.left = n4 @@ -369,134 +371,138 @@ https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%2 ```python title="binary_tree.py" -# Insert and delete a node -p = TreeNode(0) -# Insert node P between n1 and n2 -n1.left = p -p.left = n2 -# Delete node P +# Insert and remove nodes +P = TreeNode(0) +# Insert node P between n1 and n2 in n1 -> n2 +n1.left = P +P.left = n2 +# Remove node P n1.left = n2 ``` ```cpp title="binary_tree.cpp" -/* Insert and delete a node */ -TreeNode* P = new TreeNode(0); -// Insert node P between n1 and n2 +/* Insert and remove nodes */ +TreeNode *P = new TreeNode(0); +// Insert node P between n1 and n2 in n1 -> n2 n1->left = P; P->left = n2; -// Delete node P +// Remove node P n1->left = n2; -// Free the memory -delete P; +delete P; // Free memory ``` ```java title="binary_tree.java" +/* Insert and remove nodes */ TreeNode P = new TreeNode(0); -// Insert node P between n1 and n2 +// Insert node P between n1 and n2 in n1 -> n2 n1.left = P; P.left = n2; -// Delete node P +// Remove node P n1.left = n2; ``` ```csharp title="binary_tree.cs" -/* Insert and delete a node */ +/* Insert and remove nodes */ TreeNode P = new(0); -// Insert node P between n1 and n2 +// Insert node P between n1 and n2 in n1 -> n2 n1.left = P; P.left = n2; -// Delete node P +// Remove node P n1.left = n2; ``` ```go title="binary_tree.go" -/* Insert and delete a node */ -// Insert node P between n1 and n2 +/* Insert and remove nodes */ +// Insert node P between n1 and n2 in n1 -> n2 p := NewTreeNode(0) n1.Left = p p.Left = n2 -// Delete node P +// Remove node P n1.Left = n2 ``` ```swift title="binary_tree.swift" +/* Insert and remove nodes */ let P = TreeNode(x: 0) -// Insert node P between n1 and n2 +// Insert node P between n1 and n2 in n1 -> n2 n1.left = P P.left = n2 -// Delete node P +// Remove node P n1.left = n2 ``` ```javascript title="binary_tree.js" -/* Insert and delete a node */ -let P = new TreeNode(0); -// Insert node P between n1 and n2 +/* Insert and remove nodes */ +const P = new TreeNode(0); +// Insert node P between n1 and n2 in n1 -> n2 n1.left = P; P.left = n2; -// Delete node P +// Remove node P n1.left = n2; ``` ```typescript title="binary_tree.ts" -/* Insert and delete a node */ +/* Insert and remove nodes */ const P = new TreeNode(0); -// Insert node P between n1 and n2 +// Insert node P between n1 and n2 in n1 -> n2 n1.left = P; P.left = n2; -// Delete node P +// Remove node P n1.left = n2; ``` ```dart title="binary_tree.dart" -/* Insert and delete a node */ -TreeNode P = new TreeNode(0); -// Insert node P between n1 and n2 -n1.left = P; -P.left = n2; -// Delete node P +/* Insert and remove nodes */ +TreeNode p = TreeNode(0); +// Insert node P between n1 and n2 in n1 -> n2 +n1.left = p; +p.left = n2; +// Remove node P n1.left = n2; ``` ```rust title="binary_tree.rs" +/* Insert and remove nodes */ let p = TreeNode::new(0); -// Insert node P between n1 and n2 -n1.borrow_mut().left = Some(p.clone()); -p.borrow_mut().left = Some(n2.clone()); -// Delete node p -n1.borrow_mut().left = Some(n2); +// Insert node P between n1 and n2 in n1 -> n2 +p.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().left = Some(Rc::clone(&p)); +// Remove node P +drop(p); +n1.borrow_mut().left = Some(Rc::clone(&n2)); ``` ```c title="binary_tree.c" -/* Insert and delete a node */ +/* Insert and remove nodes */ TreeNode *P = newTreeNode(0); -// Insert node P between n1 and n2 +// Insert node P between n1 and n2 in n1 -> n2 n1->left = P; P->left = n2; -// Delete node P +// Remove node P n1->left = n2; -// Free the memory +// Free memory free(P); ``` ```kotlin title="binary_tree.kt" +/* Insert and remove nodes */ val P = TreeNode(0) -// Insert node P between n1 and n2 +// Insert node P between n1 and n2 in n1 -> n2 n1.left = P P.left = n2 -// Delete node P +// Remove node P n1.left = n2 ``` ```ruby title="binary_tree.rb" -# Insert and delete a node +# Insert and remove nodes _p = TreeNode.new(0) # Insert node _p between n1 and n2 n1.left = _p _p.left = n2 -# Delete the node +# Remove a node n1.left = n2 ``` -https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22Binary%20tree%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20Left%20child%20reference%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20Right%20child%20reference%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20binary%20tree%0A%20%20%20%20%23%20Initialize%20nodes%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20Connect%20nodes%20with%20references%20%28pointers%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20Insert%20and%20delete%20a%20node%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20Insert%20node%20P%20between%20n1%20and%20n2%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20Delete%20node%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22Binary%20tree%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20Left%20child%20reference%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20Right%20child%20reference%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20binary%20tree%0A%20%20%20%20%23%20Initialize%20nodes%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20Connect%20nodes%20with%20references%20%28pointers%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20Insert%20and%20delete%20a%20node%0A%20%20%20%20P%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20Insert%20node%20P%20between%20n1%20and%20n2%0A%20%20%20%20n1.left%20%3D%20P%0A%20%20%20%20P.left%20%3D%20n2%0A%20%20%20%20%23%20Delete%20node%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/en/codes/swift/chapter_hashing/built_in_hash.swift b/en/codes/swift/chapter_hashing/built_in_hash.swift index fa1198681..5761921a0 100644 --- a/en/codes/swift/chapter_hashing/built_in_hash.swift +++ b/en/codes/swift/chapter_hashing/built_in_hash.swift @@ -12,15 +12,15 @@ enum BuiltInHash { static func main() { let num = 3 let hashNum = num.hashValue - print("Hash value of integer \(num): \(hashNum)") + print("Integer \(num) has hash value \(hashNum)") let bol = true let hashBol = bol.hashValue - print("Hash value of Boolean \(bol): \(hashBol)") + print("Boolean \(bol) has hash value \(hashBol)") let dec = 3.14159 let hashDec = dec.hashValue - print("Hash value of floating-point number \(dec): \(hashDec)") + print("Floating-point number \(dec) has hash value \(hashDec)") let str = "Hello 算法" let hashStr = str.hashValue @@ -32,6 +32,6 @@ enum BuiltInHash { let obj = ListNode(x: 0) let hashObj = obj.hashValue - print("Hash value of node object \(obj): \(hashObj)") + print("Node object \(obj) has hash value \(hashObj)") } } diff --git a/en/codes/swift/chapter_stack_and_queue/array_queue.swift b/en/codes/swift/chapter_stack_and_queue/array_queue.swift index fe5a0aa28..dc1db93b3 100644 --- a/en/codes/swift/chapter_stack_and_queue/array_queue.swift +++ b/en/codes/swift/chapter_stack_and_queue/array_queue.swift @@ -107,7 +107,7 @@ enum _ArrayQueue { for i in 0 ..< 10 { queue.push(num: i) queue.pop() - print("After enqueueing and dequeueing in round \(i), queue = \(queue.toArray())") + print("After round \(i) of enqueue + dequeue, queue = \(queue.toArray())") } } } diff --git a/en/codes/swift/chapter_stack_and_queue/deque.swift b/en/codes/swift/chapter_stack_and_queue/deque.swift index 4a276a6a6..9b9805a30 100644 --- a/en/codes/swift/chapter_stack_and_queue/deque.swift +++ b/en/codes/swift/chapter_stack_and_queue/deque.swift @@ -27,7 +27,7 @@ enum Deque { print("Rear element peekLast = \(peekLast)") /* Dequeue an element */ - // When using Array as a deque, removing the first element takes O(n) time + // When using Array to simulate a deque, removeFirst has O(n) complexity let popFirst = deque.removeFirst() print("Element dequeued from the front, popFirst = \(popFirst); after dequeueing, deque = \(deque)") let popLast = deque.removeLast() diff --git a/en/codes/swift/chapter_stack_and_queue/queue.swift b/en/codes/swift/chapter_stack_and_queue/queue.swift index 69f3ae37c..b21d26058 100644 --- a/en/codes/swift/chapter_stack_and_queue/queue.swift +++ b/en/codes/swift/chapter_stack_and_queue/queue.swift @@ -25,7 +25,7 @@ enum Queue { print("Front element peek = \(peek)") /* Dequeue an element */ - // When using Array as a queue, dequeueing takes O(n) time + // When using Array as a queue, removeFirst has O(n) time complexity let pop = queue.removeFirst() print("Dequeued element pop = \(pop); after dequeueing, queue = \(queue)") diff --git a/en/codes/typescript/chapter_stack_and_queue/array_queue.ts b/en/codes/typescript/chapter_stack_and_queue/array_queue.ts index 373a5f2a5..440174d2e 100644 --- a/en/codes/typescript/chapter_stack_and_queue/array_queue.ts +++ b/en/codes/typescript/chapter_stack_and_queue/array_queue.ts @@ -103,7 +103,7 @@ console.log('Is the queue empty = ' + isEmpty); for (let i = 0; i < 10; i++) { queue.push(i); queue.pop(); - console.log('Round ' + i + ' : after enqueue + dequeue, queue =', queue.toArray()); + console.log('After round ' + i + ' of enqueue + dequeue, queue =', queue.toArray()); } export {}; diff --git a/en/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts b/en/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts index f66c9ae39..518e044fd 100644 --- a/en/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/en/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -6,8 +6,8 @@ /* Doubly linked list node */ class ListNode { - prev: ListNode; // Reference (pointer) to the previous node - next: ListNode; // Reference (pointer) to the next node + prev: ListNode | null; // Reference (pointer) to the previous node + next: ListNode | null; // Reference (pointer) to the next node val: number; // Node value constructor(val: number) { diff --git a/ja/codes/c/chapter_array_and_linkedlist/array.c b/ja/codes/c/chapter_array_and_linkedlist/array.c index 33b5c765d..49c20d03f 100644 --- a/ja/codes/c/chapter_array_and_linkedlist/array.c +++ b/ja/codes/c/chapter_array_and_linkedlist/array.c @@ -75,7 +75,7 @@ int main() { /* 配列を初期化する */ int size = 5; - int arr[5]; + int arr[5] = {0}; printf("配列 arr = "); printArray(arr, size); diff --git a/ja/codes/c/chapter_stack_and_queue/linkedlist_deque.c b/ja/codes/c/chapter_stack_and_queue/linkedlist_deque.c index 8d1872830..140f369b7 100644 --- a/ja/codes/c/chapter_stack_and_queue/linkedlist_deque.c +++ b/ja/codes/c/chapter_stack_and_queue/linkedlist_deque.c @@ -182,7 +182,7 @@ int main() { int peekFirstNum = peekFirst(deque); printf("キューの先頭要素 peekFirst = %d\r\n", peekFirstNum); int peekLastNum = peekLast(deque); - printf("キューの先頭要素 peekLast = %d\r\n", peekLastNum); + printf("キューの末尾要素 peekLast = %d\r\n", peekLastNum); /* 要素をエンキューする */ pushLast(deque, 4); diff --git a/ja/codes/c/utils/list_node.h b/ja/codes/c/utils/list_node.h index bb71448a3..ee99dd47f 100644 --- a/ja/codes/c/utils/list_node.h +++ b/ja/codes/c/utils/list_node.h @@ -14,7 +14,7 @@ extern "C" { /* 連結リストのノードの構造体 */ typedef struct ListNode { int val; // ノードの値 - struct ListNode *next; // 次のノードへの参照 + struct ListNode *next; // 次のノードへのポインタ } ListNode; /* コンストラクタ:新しいノードを初期化する */ diff --git a/ja/codes/cpp/chapter_array_and_linkedlist/array.cpp b/ja/codes/cpp/chapter_array_and_linkedlist/array.cpp index bf1bcd089..f68f95ce1 100644 --- a/ja/codes/cpp/chapter_array_and_linkedlist/array.cpp +++ b/ja/codes/cpp/chapter_array_and_linkedlist/array.cpp @@ -18,7 +18,7 @@ int randomAccess(int *nums, int size) { /* 配列の長さを拡張する */ int *extend(int *nums, int size, int enlarge) { // 拡張後の長さの配列を初期化する - int *res = new int[size + enlarge]; + int *res = new int[size + enlarge]{}; // 元の配列の全要素を新しい配列にコピーする for (int i = 0; i < size; i++) { res[i] = nums[i]; @@ -69,7 +69,7 @@ int find(int *nums, int size, int target) { int main() { /* 配列を初期化する */ int size = 5; - int *arr = new int[size]; + int *arr = new int[size]{}; cout << "配列 arr = "; printArray(arr, size); diff --git a/ja/codes/dart/chapter_hashing/hash_map.dart b/ja/codes/dart/chapter_hashing/hash_map.dart index 9c1cb4d18..beb7c9119 100644 --- a/ja/codes/dart/chapter_hashing/hash_map.dart +++ b/ja/codes/dart/chapter_hashing/hash_map.dart @@ -36,6 +36,5 @@ void main() { print("\nキー Key だけを走査する"); map.keys.forEach((key) => print(key)); print("\n値 Value だけを走査する"); - map.forEach((key, value) => print("$value")); map.values.forEach((value) => print(value)); } diff --git a/ja/codes/go/chapter_heap/heap_test.go b/ja/codes/go/chapter_heap/heap_test.go index 9a2052a4f..b7917d656 100644 --- a/ja/codes/go/chapter_heap/heap_test.go +++ b/ja/codes/go/chapter_heap/heap_test.go @@ -91,8 +91,6 @@ func TestMyHeap(t *testing.T) { } func TestTopKHeap(t *testing.T) { - /* ヒープを初期化する */ - // 最大ヒープを初期化する nums := []int{1, 7, 6, 3, 2} k := 3 res := topKHeap(nums, k) diff --git a/ja/codes/go/chapter_stack_and_queue/deque_test.go b/ja/codes/go/chapter_stack_and_queue/deque_test.go index b3b45b6ae..78d431bbb 100644 --- a/ja/codes/go/chapter_stack_and_queue/deque_test.go +++ b/ja/codes/go/chapter_stack_and_queue/deque_test.go @@ -51,7 +51,6 @@ func TestDeque(t *testing.T) { func TestArrayDeque(t *testing.T) { /* 両端キューを初期化する */ - // Go では list を両端キューとして使う deque := newArrayDeque(16) /* 要素をエンキューする */ @@ -102,7 +101,7 @@ func TestLinkedListDeque(t *testing.T) { deque.pushLast(4) deque.pushFirst(3) deque.pushFirst(1) - fmt.Print("キュー deque = ") + fmt.Print("両端キュー deque = ") PrintList(deque.toList()) // キューの先頭要素にアクセス diff --git a/ja/codes/go/chapter_stack_and_queue/queue_test.go b/ja/codes/go/chapter_stack_and_queue/queue_test.go index 66b5d95ae..ac00a6dbd 100644 --- a/ja/codes/go/chapter_stack_and_queue/queue_test.go +++ b/ja/codes/go/chapter_stack_and_queue/queue_test.go @@ -84,7 +84,7 @@ func TestArrayQueue(t *testing.T) { for i := 0; i < 10; i++ { queue.push(i) queue.pop() - fmt.Print("第", i, "回のエンキューとデキューの後 queue =") + fmt.Print("第 ", i, " 回のエンキューとデキューの後 queue =") PrintSlice(queue.toSlice()) } } diff --git a/ja/codes/java/chapter_array_and_linkedlist/list.java b/ja/codes/java/chapter_array_and_linkedlist/list.java index 276d51739..37c0a74fa 100644 --- a/ja/codes/java/chapter_array_and_linkedlist/list.java +++ b/ja/codes/java/chapter_array_and_linkedlist/list.java @@ -11,7 +11,7 @@ import java.util.*; public class list { public static void main(String[] args) { /* リストを初期化する */ - // 配列の要素型には int[] のラッパークラス Integer[] を使うことに注意 + // リストの要素には int のラッパークラス Integer しか使えないため、配列の型は int[] ではなく Integer[] にする必要があることに注意 Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); System.out.println("リスト nums = " + nums); diff --git a/ja/codes/python/chapter_hashing/built_in_hash.py b/ja/codes/python/chapter_hashing/built_in_hash.py index 45742f25d..4a0be5bb4 100644 --- a/ja/codes/python/chapter_hashing/built_in_hash.py +++ b/ja/codes/python/chapter_hashing/built_in_hash.py @@ -30,7 +30,7 @@ if __name__ == "__main__": tup = (12836, "小哈") hash_tup = hash(tup) - print(f"タプル {tup} のハッシュ値は {hash(hash_tup)}") + print(f"タプル {tup} のハッシュ値は {hash_tup}") obj = ListNode(0) hash_obj = hash(obj) diff --git a/ja/codes/ruby/chapter_hashing/built_in_hash.rb b/ja/codes/ruby/chapter_hashing/built_in_hash.rb index fcdc65930..19f8d34f9 100644 --- a/ja/codes/ruby/chapter_hashing/built_in_hash.rb +++ b/ja/codes/ruby/chapter_hashing/built_in_hash.rb @@ -24,9 +24,9 @@ if __FILE__ == $0 hash_str = str.hash puts "文字列 #{str} のハッシュ値は #{hash_str}" - tup = [12836, '小哈'] - hash_tup = tup.hash - puts "タプル #{tup} のハッシュ値は #{hash_tup}" + arr = [12836, '小哈'] + hash_arr = arr.hash + puts "配列 #{arr} のハッシュ値は #{hash_arr}" obj = ListNode.new(0) hash_obj = obj.hash diff --git a/ja/codes/ruby/chapter_stack_and_queue/array_deque.rb b/ja/codes/ruby/chapter_stack_and_queue/array_deque.rb index 723fcde57..663b7db02 100644 --- a/ja/codes/ruby/chapter_stack_and_queue/array_deque.rb +++ b/ja/codes/ruby/chapter_stack_and_queue/array_deque.rb @@ -127,13 +127,13 @@ if __FILE__ == $0 deque.push_last(4) puts "要素 4 を末尾にエンキューした後 deque = #{deque.to_array}" deque.push_first(1) - puts "要素 1 を末尾にエンキューした後 deque = #{deque.to_array}" + puts "要素 1 を先頭にエンキューした後 deque = #{deque.to_array}" # 要素をデキューする pop_last = deque.pop_last puts "末尾からデキューした要素 = #{pop_last}、末尾からデキューした後 deque = #{deque.to_array}" pop_first = deque.pop_first - puts "末尾からデキューした要素 = #{pop_first}、末尾からデキューした後 deque = #{deque.to_array}" + puts "先頭からデキューした要素 = #{pop_first}、先頭からデキューした後 deque = #{deque.to_array}" # 両端キューの長さを取得する size = deque.size diff --git a/ja/codes/ruby/chapter_stack_and_queue/deque.rb b/ja/codes/ruby/chapter_stack_and_queue/deque.rb index fd363c7b2..ca65d2827 100644 --- a/ja/codes/ruby/chapter_stack_and_queue/deque.rb +++ b/ja/codes/ruby/chapter_stack_and_queue/deque.rb @@ -30,7 +30,7 @@ if __FILE__ == $0 pop_front = deque.shift puts "先頭からデキューした要素 pop_front = #{pop_front}、先頭からデキューした後 deque = #{deque}" pop_back = deque.pop - puts "末尾からデキューした要素 pop_back = #{pop_back}, 末尾からデキューした後 deque = #{deque}" + puts "末尾からデキューした要素 pop_back = #{pop_back}、末尾からデキューした後 deque = #{deque}" # 両端キューの長さを取得する size = deque.length diff --git a/ja/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb b/ja/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb index 9dee68066..d9daaec3f 100644 --- a/ja/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/ja/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,7 +4,7 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end -### 双方向連結リストのノード +### 双方向連結リストのノード ### class ListNode attr_accessor :val attr_accessor :next # 後続ノードへの参照 @@ -101,7 +101,7 @@ class LinkedListDeque pop(true) end - ### 先頭からデキューする ### + ### 末尾からデキューする ### def pop_last pop(false) end @@ -145,7 +145,7 @@ if __FILE__ == $0 peek_first = deque.peek_first puts "キューの先頭要素 peek_first = #{peek_first}" peek_last = deque.peek_last - puts "キューの先頭要素 peek_last = #{peek_last}" + puts "キューの末尾要素 peek_last = #{peek_last}" # 要素をエンキューする deque.push_last(4) @@ -155,7 +155,7 @@ if __FILE__ == $0 # 要素をデキューする pop_last = deque.pop_last - puts "末尾からデキューした要素 = #{pop_last}, 末尾からデキューした後 deque = #{deque.to_array}" + puts "末尾からデキューした要素 = #{pop_last}、末尾からデキューした後 deque = #{deque.to_array}" pop_first = deque.pop_first puts "先頭からデキューした要素 = #{pop_first}、先頭からデキューした後 deque = #{deque.to_array}" diff --git a/ja/codes/rust/chapter_hashing/build_in_hash.rs b/ja/codes/rust/chapter_hashing/build_in_hash.rs index 6558abe81..3c49635de 100644 --- a/ja/codes/rust/chapter_hashing/build_in_hash.rs +++ b/ja/codes/rust/chapter_hashing/build_in_hash.rs @@ -45,5 +45,5 @@ fn main() { let mut hasher = DefaultHasher::new(); node.borrow().val.hash(&mut hasher); let hash = hasher.finish(); - println!("ノードオブジェクト {:?} のハッシュ値は{}", node, hash); + println!("ノードオブジェクト {:?} のハッシュ値は {}", node, hash); } diff --git a/ja/codes/snippets/chapter_array_and_linkedlist/array.md b/ja/codes/snippets/chapter_array_and_linkedlist/array.md index 27d43f0f5..9e68ff9c6 100644 --- a/ja/codes/snippets/chapter_array_and_linkedlist/array.md +++ b/ja/codes/snippets/chapter_array_and_linkedlist/array.md @@ -1,90 +1,89 @@ ```python title="array.py" -# 配列を初期化 +# 配列を初期化する arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ] nums: list[int] = [1, 3, 2, 5, 4] ``` ```cpp title="array.cpp" -/* 配列を初期化 */ -// スタック上に格納 +/* 配列を初期化する */ +// スタック上に格納する int arr[5] = {}; -int nums[5] = { 1, 3, 2, 5, 4 }; -// ヒープ上に格納(領域を手動で解放する必要がある) -int* arr1 = new int[5] {}; -int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +int nums[5] = {1, 3, 2, 5, 4}; +// ヒープ上に格納する(メモリを手動で解放する必要がある) +int *arr1 = new int[5]{}; +int *nums1 = new int[5]{1, 3, 2, 5, 4}; ``` ```java title="array.java" -/* 配列を初期化 */ +/* 配列を初期化する */ int[] arr = new int[5]; // { 0, 0, 0, 0, 0 } int[] nums = { 1, 3, 2, 5, 4 }; ``` ```csharp title="array.cs" -/* 配列を初期化 */ +// 配列を初期化する int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] int[] nums = [1, 3, 2, 5, 4]; ``` ```go title="array.go" -/* 配列を初期化 */ +/* 配列を初期化する */ var arr [5]int -// Go では、長さを指定すると([5]int)配列、指定しないと([]int)スライスになる -// Go の配列はコンパイル時に長さが決まる設計のため、長さには定数しか指定できない -// 容量を拡張する extend() メソッドを実装しやすくするため、以下ではスライス(Slice)を配列(Array)として扱う +// Go では長さを指定したもの([5]int)は配列、指定しないもの([]int)はスライスになる +// Go の配列の長さはコンパイル時に決まるため、長さの指定には定数しか使えない +// 拡張用の extend() 関数を実装しやすくするため、以下ではスライス(Slice)を配列(Array)として扱う nums := []int{1, 3, 2, 5, 4} ``` ```swift title="array.swift" -/* 配列を初期化 */ +/* 配列を初期化する */ let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] -let nums = [1, 3, 2, 5, 4] +var nums = [1, 3, 2, 5, 4] ``` ```javascript title="array.js" -/* 配列を初期化 */ -var arr = new Array(5).fill(0); -var nums = [1, 3, 2, 5, 4]; +/* 配列を初期化する */ +const arr = new Array(5).fill(0); +let nums = [1, 3, 2, 5, 4]; ``` ```typescript title="array.ts" -/* 配列を初期化 */ -let arr: number[] = new Array(5).fill(0); +/* 配列を初期化する */ +const arr: number[] = new Array(5).fill(0); let nums: number[] = [1, 3, 2, 5, 4]; ``` ```dart title="array.dart" -/* 配列を初期化 */ -List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +/* 配列を初期化する */ +var arr = List.filled(5, 0); // [0, 0, 0, 0, 0] List nums = [1, 3, 2, 5, 4]; ``` ```rust title="array.rs" -/* 配列を初期化 */ +/* 配列を初期化する */ let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] -let slice: &[i32] = &[0; 5]; -// Rust では、長さを指定すると([i32; 5])配列、指定しないと(&[i32])スライスになる -// Rust の配列はコンパイル時に長さが決まる設計のため、長さには定数しか指定できない -// Vector は、Rust で通常、動的配列として使う型 -// 容量を拡張する extend() メソッドを実装しやすくするため、以下では vector を配列(array)として扱う +// Rust では長さを指定したもの([i32; 5])は配列、指定しないもの(&[i32])はスライスになる +// Rust の配列の長さはコンパイル時に決まるため、長さの指定には定数しか使えない +// Vector は、Rust で一般に動的配列として使われる型 +// 拡張用の extend() メソッドを実装しやすくするため、以下では vector を配列(array)として扱う let nums: Vec = vec![1, 3, 2, 5, 4]; ``` ```c title="array.c" -/* 配列を初期化 */ -int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } -int nums[5] = { 1, 3, 2, 5, 4 }; +/* 配列を初期化する */ +int arr[5] = {0}; // { 0, 0, 0, 0, 0 } +int nums[] = {1, 3, 2, 5, 4}; ``` ```kotlin title="array.kt" -/* 配列を初期化 */ -var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +/* 配列を初期化する */ +val arr = IntArray(5) // { 0, 0, 0, 0, 0 } var nums = intArrayOf(1, 3, 2, 5, 4) ``` ```ruby title="array.rb" -# 配列を初期化 +# 配列を初期化する arr = Array.new(5, 0) nums = [1, 3, 2, 5, 4] ``` diff --git a/ja/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/ja/codes/snippets/chapter_array_and_linkedlist/linked_list.md index ef34436b9..17e9e9a7e 100644 --- a/ja/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/ja/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -2,48 +2,53 @@ ```python title="" class ListNode: """連結リストのノードクラス""" + def __init__(self, val: int): - self.val: int = val # ノードの値 - self.next: ListNode | None = None # 次のノードへの参照 + self.val: int = val # ノードの値 + self.next: ListNode | None = None # 次のノードへの参照 ``` ```cpp title="" -/* 連結リストのノード構造体 */ +/* 連結リストのノード */ struct ListNode { - int val; // ノードの値 - ListNode *next; // 次のノードへのポインタ - ListNode(int x) : val(x), next(nullptr) {} // コンストラクタ + int val; // ノードの値 + ListNode *next; // 後続ノードへのポインタ + ListNode(int x) : val(x), next(nullptr) { + } }; ``` ```java title="" -/* 連結リストのノードクラス */ -class ListNode { - int val; // ノードの値 - ListNode next; // 次のノードへの参照 - ListNode(int x) { val = x; } // コンストラクタ +/* 連結リストのノード */ +public class ListNode { + public int val; // ノードの値 + public ListNode next; // 次のノードへの参照 + + public ListNode(int x) { + val = x; + } } ``` ```csharp title="" -/* 連結リストのノードクラス */ -class ListNode(int x) { //コンストラクタ - public int val = x; // ノードの値 - public ListNode? next; // 次のノードへの参照 +/* 連結リストのノード */ +public class ListNode(int x) { + public int val = x; // ノードの値 + public ListNode? next; // 次のノードへの参照 } ``` ```go title="" -/* 連結リストのノード構造体 */ +// ListNode は連結リストのノード type ListNode struct { Val int // ノードの値 - Next *ListNode // 次のノードへのポインタ + Next *ListNode // 後続ノードへのポインタ } -// NewListNode コンストラクタで、新しい連結リストを作る -func NewListNode(val int) *ListNode { +// NewListNode は連結リストのノードのコンストラクタ +func NewListNode(v int) *ListNode { return &ListNode{ - Val: val, + Val: v, Next: nil, } } @@ -62,58 +67,68 @@ class ListNode { ``` ```javascript title="" -/* 連結リストのノードクラス */ +/* 連結リストのノード */ class ListNode { + val; // ノードの値 + next; // 次のノードへの参照(ポインタ) constructor(val, next) { - this.val = (val === undefined ? 0 : val); // ノードの値 - this.next = (next === undefined ? null : next); // 次のノードへの参照 + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```typescript title="" -/* 連結リストのノードクラス */ +/* 連結リストのノード */ class ListNode { - val: number; - next: ListNode | null; + val: number; // ノードの値 + next: ListNode | null; // 次のノードへの参照 constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.next = next === undefined ? null : next; // 次のノードへの参照 + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```dart title="" -/* 連結リストのノードクラス */ +/* 連結リストのノード */ class ListNode { int val; // ノードの値 ListNode? next; // 次のノードへの参照 + ListNode(this.val, [this.next]); // コンストラクタ } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; -/* 連結リストのノードクラス */ +use std::rc::Rc; + +/* 連結リストのノード */ #[derive(Debug)] -struct ListNode { - val: i32, // ノードの値 - next: Option>>, // 次のノードへのポインタ +pub struct ListNode { + pub val: T, // ノードの値 + pub next: Option>>>, // 後続ノードへのポインタ +} + +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None })) + } } ``` ```c title="" -/* 連結リストのノード構造体 */ +/* 連結リストのノードの構造体 */ typedef struct ListNode { int val; // ノードの値 struct ListNode *next; // 次のノードへのポインタ } ListNode; -/* コンストラクタ */ +/* コンストラクタ:新しいノードを初期化する */ ListNode *newListNode(int val) { ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); + node = (ListNode *)malloc(sizeof(ListNode)); node->val = val; node->next = NULL; return node; @@ -121,16 +136,14 @@ ListNode *newListNode(int val) { ``` ```kotlin title="" -/* 連結リストのノードクラス */ -// コンストラクタ -class ListNode(x: Int) { - val _val: Int = x // ノードの値 +/* 連結リストのノード */ +class ListNode(var _val: Int) { var next: ListNode? = null // 次のノードへの参照 } ``` ```ruby title="" -# 連結リストのノードクラス +### 連結リストのノードクラス ### class ListNode attr_accessor :val # ノードの値 attr_accessor :next # 次のノードへの参照 @@ -144,14 +157,14 @@ end ```python title="linked_list.py" -# 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 -# 各ノードを初期化 +# 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する +# 各ノードを初期化する n0 = ListNode(1) n1 = ListNode(3) n2 = ListNode(2) n3 = ListNode(5) n4 = ListNode(4) -# ノード間の参照を設定 +# ノード間の参照を設定する n0.next = n1 n1.next = n2 n2.next = n3 @@ -159,14 +172,14 @@ n3.next = n4 ``` ```cpp title="linked_list.cpp" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 -ListNode* n0 = new ListNode(1); -ListNode* n1 = new ListNode(3); -ListNode* n2 = new ListNode(2); -ListNode* n3 = new ListNode(5); -ListNode* n4 = new ListNode(4); -// ノード間の参照を設定 +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する */ +// 各ノードを初期化する +ListNode *n0 = new ListNode(1); +ListNode *n1 = new ListNode(3); +ListNode *n2 = new ListNode(2); +ListNode *n3 = new ListNode(5); +ListNode *n4 = new ListNode(4); +// ノード間の参照を設定する n0->next = n1; n1->next = n2; n2->next = n3; @@ -174,14 +187,14 @@ n3->next = n4; ``` ```java title="linked_list.java" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する */ +// 各ノードを初期化する ListNode n0 = new ListNode(1); ListNode n1 = new ListNode(3); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(5); ListNode n4 = new ListNode(4); -// ノード間の参照を設定 +// ノード間の参照を設定する n0.next = n1; n1.next = n2; n2.next = n3; @@ -189,14 +202,14 @@ n3.next = n4; ``` ```csharp title="linked_list.cs" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 +// 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する +// 各ノードを初期化する ListNode n0 = new(1); ListNode n1 = new(3); ListNode n2 = new(2); ListNode n3 = new(5); ListNode n4 = new(4); -// ノード間の参照を設定 +// ノード間の参照を設定する n0.next = n1; n1.next = n2; n2.next = n3; @@ -204,14 +217,15 @@ n3.next = n4; ``` ```go title="linked_list.go" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する */ +// 各ノードを初期化する n0 := NewListNode(1) n1 := NewListNode(3) n2 := NewListNode(2) n3 := NewListNode(5) n4 := NewListNode(4) -// ノード間の参照を設定 + +// ノード間の参照を設定する n0.Next = n1 n1.Next = n2 n2.Next = n3 @@ -219,14 +233,14 @@ n3.Next = n4 ``` ```swift title="linked_list.swift" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する */ +// 各ノードを初期化する let n0 = ListNode(x: 1) let n1 = ListNode(x: 3) let n2 = ListNode(x: 2) let n3 = ListNode(x: 5) let n4 = ListNode(x: 4) -// ノード間の参照を設定 +// ノード間の参照を設定する n0.next = n1 n1.next = n2 n2.next = n3 @@ -234,14 +248,14 @@ n3.next = n4 ``` ```javascript title="linked_list.js" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する */ +// 各ノードを初期化する const n0 = new ListNode(1); const n1 = new ListNode(3); const n2 = new ListNode(2); const n3 = new ListNode(5); const n4 = new ListNode(4); -// ノード間の参照を設定 +// ノード間の参照を設定する n0.next = n1; n1.next = n2; n2.next = n3; @@ -249,14 +263,14 @@ n3.next = n4; ``` ```typescript title="linked_list.ts" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する */ +// 各ノードを初期化する const n0 = new ListNode(1); const n1 = new ListNode(3); const n2 = new ListNode(2); const n3 = new ListNode(5); const n4 = new ListNode(4); -// ノード間の参照を設定 +// ノード間の参照を設定する n0.next = n1; n1.next = n2; n2.next = n3; @@ -264,14 +278,14 @@ n3.next = n4; ``` ```dart title="linked_list.dart" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 +// 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する +// 各ノードを初期化する ListNode n0 = ListNode(1); ListNode n1 = ListNode(3); ListNode n2 = ListNode(2); ListNode n3 = ListNode(5); ListNode n4 = ListNode(4); -// ノード間の参照を設定 +// ノード間の参照を設定する n0.next = n1; n1.next = n2; n2.next = n3; @@ -279,15 +293,15 @@ n3.next = n4; ``` ```rust title="linked_list.rs" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 -let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); -let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); -let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); -let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); -let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する */ +// 各ノードを初期化する +let n0 = ListNode::new(1); +let n1 = ListNode::new(3); +let n2 = ListNode::new(2); +let n3 = ListNode::new(5); +let n4 = ListNode::new(4); -// ノード間の参照を設定 +// ノード間の参照を設定する n0.borrow_mut().next = Some(n1.clone()); n1.borrow_mut().next = Some(n2.clone()); n2.borrow_mut().next = Some(n3.clone()); @@ -295,14 +309,14 @@ n3.borrow_mut().next = Some(n4.clone()); ``` ```c title="linked_list.c" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 -ListNode* n0 = newListNode(1); -ListNode* n1 = newListNode(3); -ListNode* n2 = newListNode(2); -ListNode* n3 = newListNode(5); -ListNode* n4 = newListNode(4); -// ノード間の参照を設定 +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する */ +// 各ノードを初期化する +ListNode *n0 = newListNode(1); +ListNode *n1 = newListNode(3); +ListNode *n2 = newListNode(2); +ListNode *n3 = newListNode(5); +ListNode *n4 = newListNode(4); +// ノード間の参照を設定する n0->next = n1; n1->next = n2; n2->next = n3; @@ -310,29 +324,30 @@ n3->next = n4; ``` ```kotlin title="linked_list.kt" -/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 */ -// 各ノードを初期化 +/* 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する */ +// 各ノードを初期化する val n0 = ListNode(1) val n1 = ListNode(3) val n2 = ListNode(2) val n3 = ListNode(5) val n4 = ListNode(4) -// ノード間の参照を設定 -n0.next = n1; -n1.next = n2; -n2.next = n3; -n3.next = n4; + +// ノード間の参照を設定する +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 ``` ```ruby title="linked_list.rb" -# 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化 -# 各ノードを初期化 +# 連結リスト 1 -> 3 -> 2 -> 5 -> 4 を初期化する +# 各ノードを初期化する n0 = ListNode.new(1) n1 = ListNode.new(3) n2 = ListNode.new(2) n3 = ListNode.new(5) n4 = ListNode.new(4) -# ノード間の参照を設定 +# ノード間の参照を設定する n0.next = n1 n1.next = n2 n2.next = n3 @@ -345,39 +360,46 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2 ```python title="" class ListNode: - """双方向連結リストのノードクラス""" + """双方向連結リストのノード""" + def __init__(self, val: int): - self.val: int = val # ノードの値 + """コンストラクタ""" + self.val: int = val # ノードの値 self.next: ListNode | None = None # 後続ノードへの参照 - self.prev: ListNode | None = None # 先行ノードへの参照 + self.prev: ListNode | None = None # 前のノードへの参照 ``` ```cpp title="" -/* 双方向連結リストのノード構造体 */ -struct ListNode { - int val; // ノードの値 - ListNode *next; // 後続ノードへのポインタ - ListNode *prev; // 先行ノードへのポインタ - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // コンストラクタ +/* 双方向連結リストのノード */ +struct DoublyListNode { + int val; // ノードの値 + DoublyListNode *next; // 後続ノードへのポインタ + DoublyListNode *prev; // 前のノードへのポインタ + DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { + } }; ``` ```java title="" -/* 双方向連結リストのノードクラス */ +/* 双方向連結リストのノード */ class ListNode { - int val; // ノードの値 - ListNode next; // 後続ノードへの参照 - ListNode prev; // 先行ノードへの参照 - ListNode(int x) { val = x; } // コンストラクタ + int val; // ノードの値 + ListNode next; // 後続ノードへの参照 + ListNode prev; // 前のノードへの参照 + + ListNode(int val) { + this.val = val; + prev = next = null; + } } ``` ```csharp title="" -/* 双方向連結リストのノードクラス */ -class ListNode(int x) { // コンストラクタ - public int val = x; // ノードの値 - public ListNode? next; // 後続ノードへの参照 - public ListNode? prev; // 先行ノードへの参照 +/* 双方向連結リストのノード */ +public class ListNode(int val) { + public int val = val; // ノードの値 + public ListNode? next = null; // 後続ノードへの参照 + public ListNode? prev = null; // 前のノードへの参照 } ``` @@ -400,117 +422,119 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* 双方向連結リストのノードクラス */ +/* 双方向連結リストのノード */ class ListNode { var val: Int // ノードの値 var next: ListNode? // 後続ノードへの参照 - var prev: ListNode? // 先行ノードへの参照 + weak var prev: ListNode? // 前のノードへの参照 - init(x: Int) { // コンストラクタ - val = x + init(val: Int) { + self.val = val } } ``` ```javascript title="" -/* 双方向連結リストのノードクラス */ +/* 双方向連結リストのノード */ class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.next = next === undefined ? null : next; // 後続ノードへの参照 - this.prev = prev === undefined ? null : prev; // 先行ノードへの参照 + prev; // 前のノードへの参照(ポインタ) + next; // 後続ノードへの参照(ポインタ) + val; // ノードの値 + + constructor(val) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```typescript title="" -/* 双方向連結リストのノードクラス */ +/* 双方向連結リストのノード */ class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.next = next === undefined ? null : next; // 後続ノードへの参照 - this.prev = prev === undefined ? null : prev; // 先行ノードへの参照 + prev: ListNode | null; // 前のノードへの参照(ポインタ) + next: ListNode | null; // 後続ノードへの参照(ポインタ) + val: number; // ノードの値 + + constructor(val: number) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```dart title="" -/* 双方向連結リストのノードクラス */ +/* 双方向連結リストのノード */ class ListNode { - int val; // ノードの値 - ListNode? next; // 後続ノードへの参照 - ListNode? prev; // 先行ノードへの参照 - ListNode(this.val, [this.next, this.prev]); // コンストラクタ + int val; // ノードの値 + ListNode? next; // 後続ノードへの参照 + ListNode? prev; // 前のノードへの参照 + + ListNode(this.val, {this.next, this.prev}); } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; -/* 双方向連結リストのノード型 */ -#[derive(Debug)] -struct ListNode { - val: i32, // ノードの値 - next: Option>>, // 後続ノードへのポインタ - prev: Option>>, // 先行ノードへのポインタ +/* 双方向連結リストのノード */ +pub struct ListNode { + pub val: T, // ノードの値 + pub next: Option>>>, // 後続ノードへのポインタ + pub prev: Option>>>, // 前のノードへのポインタ } -/* コンストラクタ */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None, prev: None, - } + })) } } ``` ```c title="" -/* 双方向連結リストのノード構造体 */ -typedef struct ListNode { - int val; // ノードの値 - struct ListNode *next; // 後続ノードへのポインタ - struct ListNode *prev; // 先行ノードへのポインタ -} ListNode; +/* 双方向連結リストのノード */ +typedef struct DoublyListNode { + int val; // ノードの値 + struct DoublyListNode *next; // 後続ノードへのポインタ + struct DoublyListNode *prev; // 前のノードへのポインタ +} DoublyListNode; /* コンストラクタ */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; +DoublyListNode *newDoublyListNode(int num) { + DoublyListNode *new = (DoublyListNode *)malloc(sizeof(DoublyListNode)); + new->val = num; + new->next = NULL; + new->prev = NULL; + return new; } ``` ```kotlin title="" -/* 双方向連結リストのノードクラス */ -// コンストラクタ -class ListNode(x: Int) { - val _val: Int = x // ノードの値 - var next: ListNode? = null // 後続ノードへの参照 - var prev: ListNode? = null // 先行ノードへの参照 +/* 双方向連結リストのノード */ +class ListNode( + var _val: Int // ノードの値 +) { + var next: ListNode? = null // 後続ノードへの参照 + var prev: ListNode? = null // 前のノードへの参照 } ``` ```ruby title="" -# 双方向連結リストのノードクラス +### 双方向連結リストのノード ### class ListNode - attr_accessor :val # ノードの値 - attr_accessor :next # 後続ノードへの参照 - attr_accessor :prev # 先行ノードへの参照 + attr_accessor :val # ノードの値 + attr_accessor :next # 後続ノードへの参照 + attr_accessor :prev # 前のノードへの参照 - def initialize(val=0, next_node=nil, prev_node=nil) + ### コンストラクタ ### + def initialize(val) @val = val - @next = next_node - @prev = prev_node end end ``` diff --git a/ja/codes/snippets/chapter_array_and_linkedlist/list.md b/ja/codes/snippets/chapter_array_and_linkedlist/list.md index 74ace4a03..ffd96b467 100644 --- a/ja/codes/snippets/chapter_array_and_linkedlist/list.md +++ b/ja/codes/snippets/chapter_array_and_linkedlist/list.md @@ -1,83 +1,82 @@ ```python title="list.py" -# リストを初期化 +# リストを初期化する # 初期値なし -nums1: list[int] = [] +empty_nums: list[int] = [] # 初期値あり nums: list[int] = [1, 3, 2, 5, 4] ``` ```cpp title="list.cpp" -/* リストを初期化 */ -// C++ の vector が、本節で扱う nums に相当することに注意 +/* リストを初期化する */ // 初期値なし -vector nums1; +vector emptyNums; // 初期値あり -vector nums = { 1, 3, 2, 5, 4 }; +vector nums = {1, 3, 2, 5, 4}; ``` ```java title="list.java" -/* リストを初期化 */ +/* リストを初期化する */ // 初期値なし -List nums1 = new ArrayList<>(); -// 初期値あり(配列には、int[] に対応するラッパー型の配列 Integer[] を使う必要がある) +List emptyNums = new ArrayList<>(); +// 初期値あり(リストの要素には int のラッパークラス Integer しか使えないため、配列の型は int[] ではなく Integer[] にする必要があることに注意) Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); ``` ```csharp title="list.cs" -/* リストを初期化 */ +/* リストを初期化する */ // 初期値なし -List nums1 = []; +List emptyNums = []; // 初期値あり int[] numbers = [1, 3, 2, 5, 4]; List nums = [.. numbers]; ``` ```go title="list_test.go" -/* リストを初期化 */ +/* リストを初期化する */ // 初期値なし -nums1 := []int{} +emptyNums := []int{} // 初期値あり nums := []int{1, 3, 2, 5, 4} ``` ```swift title="list.swift" -/* リストを初期化 */ +/* リストを初期化する */ // 初期値なし -let nums1: [Int] = [] +let emptyNums: [Int] = [] // 初期値あり var nums = [1, 3, 2, 5, 4] ``` ```javascript title="list.js" -/* リストを初期化 */ +/* リストを初期化する */ // 初期値なし -const nums1 = []; +const emptyNums = []; // 初期値あり const nums = [1, 3, 2, 5, 4]; ``` ```typescript title="list.ts" -/* リストを初期化 */ +/* リストを初期化する */ // 初期値なし -const nums1: number[] = []; +const emptyNums: number[] = []; // 初期値あり const nums: number[] = [1, 3, 2, 5, 4]; ``` ```dart title="list.dart" -/* リストを初期化 */ +/* リストを初期化する */ // 初期値なし -List nums1 = []; +List emptyNums = []; // 初期値あり List nums = [1, 3, 2, 5, 4]; ``` ```rust title="list.rs" -/* リストを初期化 */ +// リストを初期化する // 初期値なし -let nums1: Vec = Vec::new(); +let empty_nums: Vec = Vec::new(); // 初期値あり let mut nums: Vec = vec![1, 3, 2, 5, 4]; ``` @@ -87,103 +86,103 @@ let mut nums: Vec = vec![1, 3, 2, 5, 4]; ``` ```kotlin title="list.kt" -/* リストを初期化 */ +/* リストを初期化する */ // 初期値なし -var nums1 = listOf() +val emptyNums = mutableListOf() // 初期値あり -var numbers = arrayOf(1, 3, 2, 5, 4) -var nums = numbers.toMutableList() +val nums = mutableListOf(1, 3, 2, 5, 4) ``` ```ruby title="list.rb" -# リストを初期化 +# リストを初期化する # 初期値なし -nums1 = [] +empty_nums = [] # 初期値あり nums = [1, 3, 2, 5, 4] ``` -https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%AA%E3%81%97%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%82%E3%82%8A%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%AA%E3%81%97%0A%20%20%20%20empty_nums%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E5%88%9D%E6%9C%9F%E5%80%A4%E3%81%82%E3%82%8A%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" -# 要素にアクセス -num: int = nums[1] # インデックス 1 の要素にアクセス +# 要素にアクセスする +x: int = nums[1] # インデックス 1 の要素にアクセスする -# 要素を更新 -nums[1] = 0 # インデックス 1 の要素を 0 に更新 +# 要素を更新する +nums[1] = 0 # インデックス 1 の要素を 0 に更新する ``` ```cpp title="list.cpp" -/* 要素にアクセス */ -int num = nums[1]; // インデックス 1 の要素にアクセス +/* 要素にアクセスする */ +int num = nums[1]; // インデックス 1 の要素にアクセスする -/* 要素を更新 */ -nums[1] = 0; // インデックス 1 の要素を 0 に更新 +/* 要素を更新する */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新する ``` ```java title="list.java" -/* 要素にアクセス */ -int num = nums.get(1); // インデックス 1 の要素にアクセス +/* 要素にアクセスする */ +int num = nums.get(1); // インデックス 1 の要素にアクセスする -/* 要素を更新 */ -nums.set(1, 0); // インデックス 1 の要素を 0 に更新 +/* 要素を更新する */ +nums.set(1, 0); // インデックス 1 の要素を 0 に更新する ``` ```csharp title="list.cs" -/* 要素にアクセス */ -int num = nums[1]; // インデックス 1 の要素にアクセス +/* 要素にアクセスする */ +int num = nums[1]; // インデックス 1 の要素にアクセスする -/* 要素を更新 */ -nums[1] = 0; // インデックス 1 の要素を 0 に更新 +/* 要素を更新する */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新する ``` ```go title="list_test.go" -/* 要素にアクセス */ -num := nums[1] // インデックス 1 の要素にアクセス +/* 要素にアクセスする */ +num := nums[1] // インデックス 1 の要素にアクセスする -/* 要素を更新 */ -nums[1] = 0 // インデックス 1 の要素を 0 に更新 +/* 要素を更新する */ +nums[1] = 0 // インデックス 1 の要素を 0 に更新する ``` ```swift title="list.swift" -/* 要素にアクセス */ -let num = nums[1] // インデックス 1 の要素にアクセス +/* 要素にアクセスする */ +let num = nums[1] // インデックス 1 の要素にアクセスする -/* 要素を更新 */ -nums[1] = 0 // インデックス 1 の要素を 0 に更新 +/* 要素を更新する */ +nums[1] = 0 // インデックス 1 の要素を 0 に更新する ``` ```javascript title="list.js" -/* 要素にアクセス */ -const num = nums[1]; // インデックス 1 の要素にアクセス +/* 要素にアクセスする */ +const num = nums[1]; // インデックス 1 の要素にアクセスする -/* 要素を更新 */ -nums[1] = 0; // インデックス 1 の要素を 0 に更新 +/* 要素を更新する */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新する ``` ```typescript title="list.ts" -/* 要素にアクセス */ -const num: number = nums[1]; // インデックス 1 の要素にアクセス +/* 要素にアクセスする */ +const num: number = nums[1]; // インデックス 1 の要素にアクセスする -/* 要素を更新 */ -nums[1] = 0; // インデックス 1 の要素を 0 に更新 +/* 要素を更新する */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新する ``` ```dart title="list.dart" -/* 要素にアクセス */ -int num = nums[1]; // インデックス 1 の要素にアクセス +/* 要素にアクセスする */ +int _num = nums[1]; // インデックス 1 の要素にアクセスする -/* 要素を更新 */ -nums[1] = 0; // インデックス 1 の要素を 0 に更新 +/* 要素を更新する */ +nums[1] = 0; // インデックス 1 の要素を 0 に更新する ``` ```rust title="list.rs" -/* 要素にアクセス */ -let num: i32 = nums[1]; // インデックス 1 の要素にアクセス -/* 要素を更新 */ -nums[1] = 0; // インデックス 1 の要素を 0 に更新 +// 要素にアクセスする +let num = nums[1]; // インデックス 1 の要素にアクセスする + +// 要素を更新する +nums[1] = 0; // インデックス 1 の要素を 0 に更新する ``` ```c title="list.c" @@ -191,201 +190,203 @@ nums[1] = 0; // インデックス 1 の要素を 0 に更新 ``` ```kotlin title="list.kt" -/* 要素にアクセス */ -val num = nums[1] // インデックス 1 の要素にアクセス -/* 要素を更新 */ -nums[1] = 0 // インデックス 1 の要素を 0 に更新 +/* 要素にアクセスする */ +val num = nums[1] // インデックス 1 の要素にアクセスする + +/* 要素を更新する */ +nums[1] = 0 // インデックス 1 の要素を 0 に更新する ``` ```ruby title="list.rb" -# 要素にアクセス -num = nums[1] # インデックス 1 の要素にアクセス -# 要素を更新 -nums[1] = 0 # インデックス 1 の要素を 0 に更新 +# 要素にアクセスする +num = nums[1] # インデックス 1 の要素にアクセスする + +# 要素を更新する +nums[1] = 0 # インデックス 1 の要素を 0 に更新する ``` -https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%201%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E6%9B%B4%E6%96%B0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%201%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%200%20%E3%81%AB%E6%9B%B4%E6%96%B0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%20%20%20%20x%20%3D%20nums%5B1%5D%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%201%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%81%AB%E3%82%A2%E3%82%AF%E3%82%BB%E3%82%B9%0A%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E6%9B%B4%E6%96%B0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E3%82%A4%E3%83%B3%E3%83%87%E3%83%83%E3%82%AF%E3%82%B9%201%20%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%200%20%E3%81%AB%E6%9B%B4%E6%96%B0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" # リストを空にする nums.clear() -# 末尾に要素を追加 +# 末尾に要素を追加する nums.append(1) nums.append(3) nums.append(2) nums.append(5) nums.append(4) -# 途中に要素を挿入 -nums.insert(3, 6) # インデックス 3 に数値 6 を挿入 +# 途中に要素を挿入する +nums.insert(3, 6) # インデックス 3 に数値 6 を挿入する -# 要素を削除 -nums.pop(3) # インデックス 3 の要素を削除 +# 要素を削除する +nums.pop(3) # インデックス 3 の要素を削除する ``` ```cpp title="list.cpp" /* リストを空にする */ nums.clear(); -/* 末尾に要素を追加 */ +/* 末尾に要素を追加する */ nums.push_back(1); nums.push_back(3); nums.push_back(2); nums.push_back(5); nums.push_back(4); -/* 途中に要素を挿入 */ -nums.insert(nums.begin() + 3, 6); // インデックス 3 に数値 6 を挿入 +/* 途中に要素を挿入する */ +nums.insert(nums.begin() + 3, 6); // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums.erase(nums.begin() + 3); // インデックス 3 の要素を削除 +/* 要素を削除する */ +nums.erase(nums.begin() + 3); // インデックス 3 の要素を削除する ``` ```java title="list.java" /* リストを空にする */ nums.clear(); -/* 末尾に要素を追加 */ +/* 末尾に要素を追加する */ nums.add(1); nums.add(3); nums.add(2); nums.add(5); nums.add(4); -/* 途中に要素を挿入 */ -nums.add(3, 6); // インデックス 3 に数値 6 を挿入 +/* 途中に要素を挿入する */ +nums.add(3, 6); // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums.remove(3); // インデックス 3 の要素を削除 +/* 要素を削除する */ +nums.remove(3); // インデックス 3 の要素を削除する ``` ```csharp title="list.cs" /* リストを空にする */ nums.Clear(); -/* 末尾に要素を追加 */ +/* 末尾に要素を追加する */ nums.Add(1); nums.Add(3); nums.Add(2); nums.Add(5); nums.Add(4); -/* 途中に要素を挿入 */ -nums.Insert(3, 6); // インデックス 3 に数値 6 を挿入 +/* 途中に要素を挿入する */ +nums.Insert(3, 6); // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums.RemoveAt(3); // インデックス 3 の要素を削除 +/* 要素を削除する */ +nums.RemoveAt(3); // インデックス 3 の要素を削除する ``` ```go title="list_test.go" /* リストを空にする */ nums = nil -/* 末尾に要素を追加 */ +/* 末尾に要素を追加する */ nums = append(nums, 1) nums = append(nums, 3) nums = append(nums, 2) nums = append(nums, 5) nums = append(nums, 4) -/* 途中に要素を挿入 */ -nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // インデックス 3 に数値 6 を挿入 +/* 途中に要素を挿入する */ +nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums = append(nums[:3], nums[4:]...) // インデックス 3 の要素を削除 +/* 要素を削除する */ +nums = append(nums[:3], nums[4:]...) // インデックス 3 の要素を削除する ``` ```swift title="list.swift" /* リストを空にする */ nums.removeAll() -/* 末尾に要素を追加 */ +/* 末尾に要素を追加する */ nums.append(1) nums.append(3) nums.append(2) nums.append(5) nums.append(4) -/* 途中に要素を挿入 */ -nums.insert(6, at: 3) // インデックス 3 に数値 6 を挿入 +/* 途中に要素を挿入する */ +nums.insert(6, at: 3) // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums.remove(at: 3) // インデックス 3 の要素を削除 +/* 要素を削除する */ +nums.remove(at: 3) // インデックス 3 の要素を削除する ``` ```javascript title="list.js" /* リストを空にする */ nums.length = 0; -/* 末尾に要素を追加 */ +/* 末尾に要素を追加する */ nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* 途中に要素を挿入 */ -nums.splice(3, 0, 6); // インデックス 3 に数値 6 を挿入 +/* 途中に要素を挿入する */ +nums.splice(3, 0, 6); // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums.splice(3, 1); // インデックス 3 の要素を削除 +/* 要素を削除する */ +nums.splice(3, 1); // インデックス 3 の要素を削除する ``` ```typescript title="list.ts" /* リストを空にする */ nums.length = 0; -/* 末尾に要素を追加 */ +/* 末尾に要素を追加する */ nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* 途中に要素を挿入 */ -nums.splice(3, 0, 6); // インデックス 3 に数値 6 を挿入 +/* 途中に要素を挿入する */ +nums.splice(3, 0, 6); // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums.splice(3, 1); // インデックス 3 の要素を削除 +/* 要素を削除する */ +nums.splice(3, 1); // インデックス 3 の要素を削除する ``` ```dart title="list.dart" /* リストを空にする */ nums.clear(); -/* 末尾に要素を追加 */ +/* 末尾に要素を追加する */ nums.add(1); nums.add(3); nums.add(2); nums.add(5); nums.add(4); -/* 途中に要素を挿入 */ -nums.insert(3, 6); // インデックス 3 に数値 6 を挿入 +/* 途中に要素を挿入する */ +nums.insert(3, 6); // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums.removeAt(3); // インデックス 3 の要素を削除 +/* 要素を削除する */ +nums.removeAt(3); // インデックス 3 の要素を削除する ``` ```rust title="list.rs" -/* リストを空にする */ +// リストを空にする nums.clear(); -/* 末尾に要素を追加 */ +// 末尾に要素を追加する nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* 途中に要素を挿入 */ -nums.insert(3, 6); // インデックス 3 に数値 6 を挿入 +// 途中に要素を挿入する +nums.insert(3, 6); // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums.remove(3); // インデックス 3 の要素を削除 +// 要素を削除する +nums.remove(3); // インデックス 3 の要素を削除する ``` ```c title="list.c" @@ -394,38 +395,38 @@ nums.remove(3); // インデックス 3 の要素を削除 ```kotlin title="list.kt" /* リストを空にする */ -nums.clear(); +nums.clear() -/* 末尾に要素を追加 */ -nums.add(1); -nums.add(3); -nums.add(2); -nums.add(5); -nums.add(4); +/* 末尾に要素を追加する */ +nums.add(1) +nums.add(3) +nums.add(2) +nums.add(5) +nums.add(4) -/* 途中に要素を挿入 */ -nums.add(3, 6); // インデックス 3 に数値 6 を挿入 +/* 途中に要素を挿入する */ +nums.add(3, 6) // インデックス 3 に数値 6 を挿入する -/* 要素を削除 */ -nums.removeAt(3); // インデックス 3 の要素を削除 +/* 要素を削除する */ +nums.removeAt(3) // インデックス 3 の要素を削除する ``` ```ruby title="list.rb" # リストを空にする nums.clear -# 末尾に要素を追加 +# 末尾に要素を追加する nums << 1 nums << 3 nums << 2 nums << 5 nums << 4 -# 途中に要素を挿入 -nums.insert(3, 6) # インデックス 3 に数値 6 を挿入 +# 途中に要素を挿入する +nums.insert(3, 6) # インデックス 3 に数値 6 を挿入する -# 要素を削除 -nums.delete_at(3) # インデックス 3 の要素を削除 +# 要素を削除する +nums.delete_at(3) # インデックス 3 の要素を削除する ``` @@ -433,138 +434,138 @@ https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3 ```python title="list.py" -# インデックスを使ってリストを走査 +# インデックスを使ってリストを走査する count = 0 for i in range(len(nums)): count += nums[i] -# リストの要素を直接走査 +# リストの要素を直接走査する for num in nums: count += num ``` ```cpp title="list.cpp" -/* インデックスを使ってリストを走査 */ +/* インデックスを使ってリストを走査する */ int count = 0; for (int i = 0; i < nums.size(); i++) { count += nums[i]; } -/* リストの要素を直接走査 */ +/* リストの要素を直接走査する */ count = 0; -for (int num : nums) { - count += num; +for (int x : nums) { + count += x; } ``` ```java title="list.java" -/* インデックスを使ってリストを走査 */ +/* インデックスを使ってリストを走査する */ int count = 0; for (int i = 0; i < nums.size(); i++) { count += nums.get(i); } -/* リストの要素を直接走査 */ -for (int num : nums) { - count += num; +/* リストの要素を直接走査する */ +for (int x : nums) { + count += x; } ``` ```csharp title="list.cs" -/* インデックスを使ってリストを走査 */ +/* インデックスを使ってリストを走査する */ int count = 0; for (int i = 0; i < nums.Count; i++) { count += nums[i]; } -/* リストの要素を直接走査 */ +/* リストの要素を直接走査する */ count = 0; -foreach (int num in nums) { - count += num; +foreach (int x in nums) { + count += x; } ``` ```go title="list_test.go" -/* インデックスを使ってリストを走査 */ +/* インデックスを使ってリストを走査する */ count := 0 for i := 0; i < len(nums); i++ { count += nums[i] } -/* リストの要素を直接走査 */ +/* リストの要素を直接走査する */ count = 0 -for _, num := range nums { - count += num +for _, x := range nums { + count += x } ``` ```swift title="list.swift" -/* インデックスを使ってリストを走査 */ +/* インデックスを使ってリストを走査する */ var count = 0 for i in nums.indices { count += nums[i] } -/* リストの要素を直接走査 */ +/* リストの要素を直接走査する */ count = 0 -for num in nums { - count += num +for x in nums { + count += x } ``` ```javascript title="list.js" -/* インデックスを使ってリストを走査 */ +/* インデックスを使ってリストを走査する */ let count = 0; for (let i = 0; i < nums.length; i++) { count += nums[i]; } -/* リストの要素を直接走査 */ +/* リストの要素を直接走査する */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` ```typescript title="list.ts" -/* インデックスを使ってリストを走査 */ +/* インデックスを使ってリストを走査する */ let count = 0; for (let i = 0; i < nums.length; i++) { count += nums[i]; } -/* リストの要素を直接走査 */ +/* リストの要素を直接走査する */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` ```dart title="list.dart" -/* インデックスを使ってリストを走査 */ +/* インデックスを使ってリストを走査する */ int count = 0; for (var i = 0; i < nums.length; i++) { - count += nums[i]; + count += nums[i]; } -/* リストの要素を直接走査 */ +/* リストの要素を直接走査する */ count = 0; -for (var num in nums) { - count += num; +for (var x in nums) { + count += x; } ``` ```rust title="list.rs" -// インデックスを使ってリストを走査 +// インデックスを使ってリストを走査する let mut _count = 0; for i in 0..nums.len() { _count += nums[i]; } -// リストの要素を直接走査 +// リストの要素を直接走査する _count = 0; -for num in &nums { - _count += num; +for x in &nums { + _count += x; } ``` @@ -573,29 +574,29 @@ for num in &nums { ``` ```kotlin title="list.kt" -/* インデックスを使ってリストを走査 */ +/* インデックスを使ってリストを走査する */ var count = 0 for (i in nums.indices) { count += nums[i] } -/* リストの要素を直接走査 */ -for (num in nums) { - count += num +/* リストの要素を直接走査する */ +for (j in nums) { + count += j } ``` ```ruby title="list.rb" -# インデックスを使ってリストを走査 +# インデックスを使ってリストを走査する count = 0 for i in 0...nums.length - count += nums[i] + count += nums[i] end -# リストの要素を直接走査 +# リストの要素を直接走査する count = 0 -for num in nums - count += num +nums.each do |x| + count += x end ``` @@ -604,64 +605,64 @@ https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3 ```python title="list.py" -# 二つのリストを連結 -nums1: list[int] = [6, 8, 7, 10, 9] -nums += nums1 # リスト nums1 を nums の後ろに連結 +# 2 つのリストを連結する +nums1 = [6, 8, 7, 10, 9] +nums += nums1 # リスト nums の後ろに nums1 を連結する ``` ```cpp title="list.cpp" -/* 二つのリストを連結 */ -vector nums1 = { 6, 8, 7, 10, 9 }; -// リスト nums1 を nums の後ろに連結 +/* 2 つのリストを連結する */ +vector nums1 = {6, 8, 7, 10, 9}; +// リスト nums の後ろに nums1 を連結する nums.insert(nums.end(), nums1.begin(), nums1.end()); ``` ```java title="list.java" -/* 二つのリストを連結 */ +/* 2 つのリストを連結する */ List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); -nums.addAll(nums1); // リスト nums1 を nums の後ろに連結 +nums.addAll(nums1); // リスト nums の後ろに nums1 を連結する ``` ```csharp title="list.cs" -/* 二つのリストを連結 */ +/* 2 つのリストを連結する */ List nums1 = [6, 8, 7, 10, 9]; -nums.AddRange(nums1); // リスト nums1 を nums の後ろに連結 +nums.AddRange(nums1); // リスト nums の後ろに nums1 を連結する ``` ```go title="list_test.go" -/* 二つのリストを連結 */ +/* 2 つのリストを連結する */ nums1 := []int{6, 8, 7, 10, 9} -nums = append(nums, nums1...) // リスト nums1 を nums の後ろに連結 +nums = append(nums, nums1...) // リスト nums の後ろに nums1 を連結する ``` ```swift title="list.swift" -/* 二つのリストを連結 */ +/* 2 つのリストを連結する */ let nums1 = [6, 8, 7, 10, 9] -nums.append(contentsOf: nums1) // リスト nums1 を nums の後ろに連結 +nums.append(contentsOf: nums1) // リスト nums の後ろに nums1 を連結する ``` ```javascript title="list.js" -/* 二つのリストを連結 */ +/* 2 つのリストを連結する */ const nums1 = [6, 8, 7, 10, 9]; -nums.push(...nums1); // リスト nums1 を nums の後ろに連結 +nums.push(...nums1); // リスト nums の後ろに nums1 を連結する ``` ```typescript title="list.ts" -/* 二つのリストを連結 */ +/* 2 つのリストを連結する */ const nums1: number[] = [6, 8, 7, 10, 9]; -nums.push(...nums1); // リスト nums1 を nums の後ろに連結 +nums.push(...nums1); // リスト nums の後ろに nums1 を連結する ``` ```dart title="list.dart" -/* 二つのリストを連結 */ +/* 2 つのリストを連結する */ List nums1 = [6, 8, 7, 10, 9]; -nums.addAll(nums1); // リスト nums1 を nums の後ろに連結 +nums.addAll(nums1); // リスト nums の後ろに nums1 を連結する ``` ```rust title="list.rs" -/* 二つのリストを連結 */ -let nums1: Vec = vec![6, 8, 7, 10, 9]; -nums.extend(nums1); +// 2 つのリストを連結する +let mut nums1 = vec![6, 8, 7, 10, 9]; +nums.append(&mut nums1); // append は nums1 の要素をムーブするため、その後 nums1 は空になる ``` ```c title="list.c" @@ -669,13 +670,13 @@ nums.extend(nums1); ``` ```kotlin title="list.kt" -/* 二つのリストを連結 */ -val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() -nums.addAll(nums1) // リスト nums1 を nums の後ろに連結 +/* 2 つのリストを連結する */ +val nums1 = mutableListOf(6, 8, 7, 10, 9) +nums.addAll(nums1) // リスト nums の後ろに nums1 を連結する ``` ```ruby title="list.rb" -# 二つのリストを連結 +# 2 つのリストを連結する nums1 = [6, 8, 7, 10, 9] nums += nums1 ``` @@ -685,52 +686,52 @@ https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3 ```python title="list.py" -# リストをソート +# リストをソートする nums.sort() # ソート後、リストの要素は昇順に並ぶ ``` ```cpp title="list.cpp" -/* リストをソート */ -sort(nums.begin(), nums.end()); // ソート後、リストの要素は昇順に並ぶ +/* リストをソートする */ +sort(nums.begin(), nums.end()); // ソート後、リストの要素は昇順に並ぶ ``` ```java title="list.java" -/* リストをソート */ -Collections.sort(nums); // ソート後、リストの要素は昇順に並ぶ +/* リストをソートする */ +Collections.sort(nums); // ソート後、リストの要素は昇順に並ぶ ``` ```csharp title="list.cs" -/* リストをソート */ +/* リストをソートする */ nums.Sort(); // ソート後、リストの要素は昇順に並ぶ ``` ```go title="list_test.go" -/* リストをソート */ -sort.Ints(nums) // ソート後、リストの要素は昇順に並ぶ +/* リストをソートする */ +sort.Ints(nums) // ソート後、リストの要素は昇順に並ぶ ``` ```swift title="list.swift" -/* リストをソート */ +/* リストをソートする */ nums.sort() // ソート後、リストの要素は昇順に並ぶ ``` ```javascript title="list.js" -/* リストをソート */ -nums.sort((a, b) => a - b); // ソート後、リストの要素は昇順に並ぶ +/* リストをソートする */ +nums.sort((a, b) => a - b); // ソート後、リストの要素は昇順に並ぶ ``` ```typescript title="list.ts" -/* リストをソート */ -nums.sort((a, b) => a - b); // ソート後、リストの要素は昇順に並ぶ +/* リストをソートする */ +nums.sort((a, b) => a - b); // ソート後、リストの要素は昇順に並ぶ ``` ```dart title="list.dart" -/* リストをソート */ +/* リストをソートする */ nums.sort(); // ソート後、リストの要素は昇順に並ぶ ``` ```rust title="list.rs" -/* リストをソート */ +// リストをソートする nums.sort(); // ソート後、リストの要素は昇順に並ぶ ``` @@ -739,12 +740,12 @@ nums.sort(); // ソート後、リストの要素は昇順に並ぶ ``` ```kotlin title="list.kt" -/* リストをソート */ +/* リストをソートする */ nums.sort() // ソート後、リストの要素は昇順に並ぶ ``` ```ruby title="list.rb" -# リストをソート +# リストをソートする nums = nums.sort { |a, b| a <=> b } # ソート後、リストの要素は昇順に並ぶ ``` diff --git a/ja/codes/snippets/chapter_hashing/hash_algorithm.md b/ja/codes/snippets/chapter_hashing/hash_algorithm.md index ce7ccbdc1..ac2f5a85f 100644 --- a/ja/codes/snippets/chapter_hashing/hash_algorithm.md +++ b/ja/codes/snippets/chapter_hashing/hash_algorithm.md @@ -2,100 +2,122 @@ ```python title="built_in_hash.py" num = 3 hash_num = hash(num) +print(f"整数 {num} のハッシュ値は {hash_num}") # 整数 3 のハッシュ値は 3 bol = True hash_bol = hash(bol) +print(f"真偽値 {bol} のハッシュ値は {hash_bol}") # 真偽値 True のハッシュ値は 1 dec = 3.14159 hash_dec = hash(dec) +print(f"小数 {dec} のハッシュ値は {hash_dec}") # 小数 3.14159 のハッシュ値は 326484311674566659 str = "Hello 算法" hash_str = hash(str) +print(f"文字列「{str}」のハッシュ値は {hash_str}") # 文字列「Hello 算法」のハッシュ値は 4617003410720528961 tup = (12836, "小哈") hash_tup = hash(tup) +print(f"タプル {tup} のハッシュ値は {hash_tup}") # タプル (12836, '小哈') のハッシュ値は 1029005403108185979 obj = ListNode(0) hash_obj = hash(obj) -# ノードオブジェクト のハッシュ値は 274267521 +print(f"ノードオブジェクト {obj} のハッシュ値は {hash_obj}") +# ノードオブジェクト のハッシュ値は 274267521 ``` ```cpp title="built_in_hash.cpp" int num = 3; size_t hashNum = hash()(num); +cout << "整数 " << num << " のハッシュ値は " << hashNum << "\n"; // 整数 3 のハッシュ値は 3 bool bol = true; size_t hashBol = hash()(bol); +cout << "真偽値 " << bol << " のハッシュ値は " << hashBol << "\n"; // 真偽値 1 のハッシュ値は 1 double dec = 3.14159; size_t hashDec = hash()(dec); +cout << "小数 " << dec << " のハッシュ値は " << hashDec << "\n"; // 小数 3.14159 のハッシュ値は 4614256650576692846 string str = "Hello 算法"; size_t hashStr = hash()(str); +cout << "文字列「" << str << "」のハッシュ値は " << hashStr << "\n"; // 文字列「Hello 算法」のハッシュ値は 15466937326284535026 -// C++ の組み込み std::hash() は基本データ型のハッシュ値計算のみを提供する -// 配列やオブジェクトのハッシュ値計算は自分で実装する +// C++ の組み込み std::hash() は、基本データ型のハッシュ値の計算にのみ対応する +// 配列やオブジェクトのハッシュ値の計算は自分で実装する必要がある ``` ```java title="built_in_hash.java" int num = 3; int hashNum = Integer.hashCode(num); +System.out.println("整数 " + num + " のハッシュ値は " + hashNum); // 整数 3 のハッシュ値は 3 boolean bol = true; int hashBol = Boolean.hashCode(bol); +System.out.println("真偽値 " + bol + " のハッシュ値は " + hashBol); // 真偽値 true のハッシュ値は 1231 double dec = 3.14159; int hashDec = Double.hashCode(dec); +System.out.println("小数 " + dec + " のハッシュ値は " + hashDec); // 小数 3.14159 のハッシュ値は -1340954729 String str = "Hello 算法"; int hashStr = str.hashCode(); +System.out.println("文字列「" + str + "」のハッシュ値は " + hashStr); // 文字列「Hello 算法」のハッシュ値は -727081396 Object[] arr = { 12836, "小哈" }; -int hashTup = Arrays.hashCode(arr); +int hashArr = Arrays.hashCode(arr); +System.out.println("配列 " + Arrays.toString(arr) + " のハッシュ値は " + hashArr); // 配列 [12836, 小哈] のハッシュ値は 1151158 ListNode obj = new ListNode(0); int hashObj = obj.hashCode(); +System.out.println("ノードオブジェクト " + obj + " のハッシュ値は " + hashObj); // ノードオブジェクト utils.ListNode@7dc5e7b4 のハッシュ値は 2110121908 ``` ```csharp title="built_in_hash.cs" int num = 3; int hashNum = num.GetHashCode(); -// 整数 3 のハッシュ値は 3; +Console.WriteLine("整数 " + num + " のハッシュ値は " + hashNum); +// 整数 3 のハッシュ値は 3 bool bol = true; int hashBol = bol.GetHashCode(); -// 真偽値 true のハッシュ値は 1; +Console.WriteLine("真偽値 " + bol + " のハッシュ値は " + hashBol); +// 真偽値 True のハッシュ値は 1 double dec = 3.14159; int hashDec = dec.GetHashCode(); -// 小数 3.14159 のハッシュ値は -1340954729; +Console.WriteLine("小数 " + dec + " のハッシュ値は " + hashDec); +// 小数 3.14159 のハッシュ値は -1340954729 string str = "Hello 算法"; int hashStr = str.GetHashCode(); -// 文字列「Hello 算法」のハッシュ値は -586107568; +Console.WriteLine("文字列「" + str + "」のハッシュ値は " + hashStr); +// 文字列「Hello 算法」のハッシュ値は -586107568 object[] arr = [12836, "小哈"]; -int hashTup = arr.GetHashCode(); -// 配列 [12836, 小哈] のハッシュ値は 42931033; +int hashArr = arr.GetHashCode(); +Console.WriteLine("配列 [" + string.Join(", ", arr) + "] のハッシュ値は " + hashArr); +// 配列 [12836, 小哈] のハッシュ値は 42931033 ListNode obj = new(0); int hashObj = obj.GetHashCode(); -// ノードオブジェクト 0 のハッシュ値は 39053774; +Console.WriteLine("ノードオブジェクト " + obj + " のハッシュ値は " + hashObj); +// ノードオブジェクト 0 のハッシュ値は 39053774 ``` ```go title="built_in_hash.go" @@ -105,26 +127,32 @@ int hashObj = obj.GetHashCode(); ```swift title="built_in_hash.swift" let num = 3 let hashNum = num.hashValue +print("整数 \(num) のハッシュ値は \(hashNum)") // 整数 3 のハッシュ値は 9047044699613009734 let bol = true let hashBol = bol.hashValue +print("真偽値 \(bol) のハッシュ値は \(hashBol)") // 真偽値 true のハッシュ値は -4431640247352757451 let dec = 3.14159 let hashDec = dec.hashValue +print("小数 \(dec) のハッシュ値は \(hashDec)") // 小数 3.14159 のハッシュ値は -2465384235396674631 let str = "Hello 算法" let hashStr = str.hashValue +print("文字列「\(str)」のハッシュ値は \(hashStr)") // 文字列「Hello 算法」のハッシュ値は -7850626797806988787 let arr = [AnyHashable(12836), AnyHashable("小哈")] -let hashTup = arr.hashValue +let hashArr = arr.hashValue +print("配列 \(arr) のハッシュ値は \(hashArr)") // 配列 [AnyHashable(12836), AnyHashable("小哈")] のハッシュ値は -2308633508154532996 let obj = ListNode(x: 0) let hashObj = obj.hashValue +print("ノードオブジェクト \(obj) のハッシュ値は \(hashObj)") // ノードオブジェクト utils.ListNode のハッシュ値は -2434780518035996159 ``` @@ -139,26 +167,32 @@ let hashObj = obj.hashValue ```dart title="built_in_hash.dart" int num = 3; int hashNum = num.hashCode; +print("整数 $num のハッシュ値は $hashNum"); // 整数 3 のハッシュ値は 34803 bool bol = true; int hashBol = bol.hashCode; +print("真偽値 $bol のハッシュ値は $hashBol"); // 真偽値 true のハッシュ値は 1231 double dec = 3.14159; int hashDec = dec.hashCode; +print("小数 $dec のハッシュ値は $hashDec"); // 小数 3.14159 のハッシュ値は 2570631074981783 String str = "Hello 算法"; int hashStr = str.hashCode; +print("文字列「$str」のハッシュ値は $hashStr"); // 文字列「Hello 算法」のハッシュ値は 468167534 List arr = [12836, "小哈"]; int hashArr = arr.hashCode; +print("配列 $arr のハッシュ値は $hashArr"); // 配列 [12836, 小哈] のハッシュ値は 976512528 -ListNode obj = new ListNode(0); +ListNode obj = ListNode(0); int hashObj = obj.hashCode; +print("ノードオブジェクト $obj のハッシュ値は $hashObj"); // ノードオブジェクト Instance of 'ListNode' のハッシュ値は 1033450432 ``` @@ -170,36 +204,42 @@ let num = 3; let mut num_hasher = DefaultHasher::new(); num.hash(&mut num_hasher); let hash_num = num_hasher.finish(); +println!("整数 {} のハッシュ値は {}", num, hash_num); // 整数 3 のハッシュ値は 568126464209439262 let bol = true; let mut bol_hasher = DefaultHasher::new(); bol.hash(&mut bol_hasher); let hash_bol = bol_hasher.finish(); +println!("真偽値 {} のハッシュ値は {}", bol, hash_bol); // 真偽値 true のハッシュ値は 4952851536318644461 let dec: f32 = 3.14159; let mut dec_hasher = DefaultHasher::new(); dec.to_bits().hash(&mut dec_hasher); let hash_dec = dec_hasher.finish(); +println!("小数 {} のハッシュ値は {}", dec, hash_dec); // 小数 3.14159 のハッシュ値は 2566941990314602357 let str = "Hello 算法"; let mut str_hasher = DefaultHasher::new(); str.hash(&mut str_hasher); let hash_str = str_hasher.finish(); +println!("文字列「{}」のハッシュ値は {}", str, hash_str); // 文字列「Hello 算法」のハッシュ値は 16092673739211250988 -let arr = (&12836, &"小哈"); +let tup = (&12836, &"小哈"); let mut tup_hasher = DefaultHasher::new(); -arr.hash(&mut tup_hasher); +tup.hash(&mut tup_hasher); let hash_tup = tup_hasher.finish(); +println!("タプル {:?} のハッシュ値は {}", tup, hash_tup); // タプル (12836, "小哈") のハッシュ値は 1885128010422702749 let node = ListNode::new(42); -let mut hasher = DefaultHasher::new(); -node.borrow().val.hash(&mut hasher); -let hash = hasher.finish(); +let mut node_hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut node_hasher); +let hash_node = node_hasher.finish(); +println!("ノードオブジェクト {:?} のハッシュ値は {}", node, hash_node); // ノードオブジェクト RefCell { value: ListNode { val: 42, next: None } } のハッシュ値は 15387811073369036852 ``` @@ -210,54 +250,66 @@ let hash = hasher.finish(); ```kotlin title="built_in_hash.kt" val num = 3 val hashNum = num.hashCode() +println("整数 $num のハッシュ値は $hashNum") // 整数 3 のハッシュ値は 3 val bol = true val hashBol = bol.hashCode() +println("真偽値 $bol のハッシュ値は $hashBol") // 真偽値 true のハッシュ値は 1231 val dec = 3.14159 val hashDec = dec.hashCode() +println("小数 $dec のハッシュ値は $hashDec") // 小数 3.14159 のハッシュ値は -1340954729 val str = "Hello 算法" val hashStr = str.hashCode() +println("文字列「$str」のハッシュ値は $hashStr") // 文字列「Hello 算法」のハッシュ値は -727081396 val arr = arrayOf(12836, "小哈") -val hashTup = arr.hashCode() -// 配列 [12836, 小哈] のハッシュ値は 189568618 +val hashArr = arr.contentHashCode() +println("配列 ${arr.contentToString()} のハッシュ値は $hashArr") +// 配列 [12836, 小哈] のハッシュ値は 1151158 val obj = ListNode(0) val hashObj = obj.hashCode() +println("ノードオブジェクト $obj のハッシュ値は $hashObj") // ノードオブジェクト utils.ListNode@1d81eb93 のハッシュ値は 495053715 ``` ```ruby title="built_in_hash.rb" num = 3 hash_num = num.hash +puts "整数 #{num} のハッシュ値は #{hash_num}" # 整数 3 のハッシュ値は -4385856518450339636 bol = true hash_bol = bol.hash +puts "真偽値 #{bol} のハッシュ値は #{hash_bol}" # 真偽値 true のハッシュ値は -1617938112149317027 dec = 3.14159 hash_dec = dec.hash +puts "小数 #{dec} のハッシュ値は #{hash_dec}" # 小数 3.14159 のハッシュ値は -1479186995943067893 str = "Hello 算法" hash_str = str.hash +puts "文字列「#{str}」のハッシュ値は #{hash_str}" # 文字列「Hello 算法」のハッシュ値は -4075943250025831763 -tup = [12836, '小哈'] -hash_tup = tup.hash -# タプル (12836, '小哈') のハッシュ値は 1999544809202288822 +arr = [12836, '小哈'] +hash_arr = arr.hash +puts "配列 #{arr} のハッシュ値は #{hash_arr}" +# 配列 [12836, "小哈"] のハッシュ値は 1999544809202288822 obj = ListNode.new(0) hash_obj = obj.hash +puts "ノードオブジェクト #{obj} のハッシュ値は #{hash_obj}" # ノードオブジェクト # のハッシュ値は 4302940560806366381 ``` -https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E6%AC%A1%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash(num)%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash(bol)%0A%20%20%20%20%23%20%E7%9C%9F%E5%81%BD%E5%80%A4%20True%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash(dec)%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash(str)%0A%20%20%20%20%23%20%E6%96%87%E5%AD%97%E5%88%97%E3%80%8CHello%20%E7%AE%97%E6%B3%95%E3%80%8D%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20(12836%2C%20%22%E5%B0%8F%E5%93%88%22)%0A%20%20%20%20hash_tup%20%3D%20hash(tup)%0A%20%20%20%20%23%20%E3%82%BF%E3%83%97%E3%83%AB%20(12836%2C%20'%E5%B0%8F%E5%93%88')%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode(0)%0A%20%20%20%20hash_obj%20%3D%20hash(obj)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%20%3CListNode%20object%20at%200x1058fd810%3E%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%80%A3%E7%B5%90%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E6%AC%A1%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash(num)%0A%20%20%20%20print(f%22%E6%95%B4%E6%95%B0%20%7Bnum%7D%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20%7Bhash_num%7D%22)%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash(bol)%0A%20%20%20%20print(f%22%E7%9C%9F%E5%81%BD%E5%80%A4%20%7Bbol%7D%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20%7Bhash_bol%7D%22)%0A%20%20%20%20%23%20%E7%9C%9F%E5%81%BD%E5%80%A4%20True%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash(dec)%0A%20%20%20%20print(f%22%E5%B0%8F%E6%95%B0%20%7Bdec%7D%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20%7Bhash_dec%7D%22)%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash(str)%0A%20%20%20%20print(f%22%E6%96%87%E5%AD%97%E5%88%97%E3%80%8C%7Bstr%7D%E3%80%8D%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20%7Bhash_str%7D%22)%0A%20%20%20%20%23%20%E6%96%87%E5%AD%97%E5%88%97%E3%80%8CHello%20%E7%AE%97%E6%B3%95%E3%80%8D%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20(12836%2C%20%22%E5%B0%8F%E5%93%88%22)%0A%20%20%20%20hash_tup%20%3D%20hash(tup)%0A%20%20%20%20print(f%22%E3%82%BF%E3%83%97%E3%83%AB%20%7Btup%7D%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20%7Bhash_tup%7D%22)%0A%20%20%20%20%23%20%E3%82%BF%E3%83%97%E3%83%AB%20(12836%2C%20'%E5%B0%8F%E5%93%88')%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode(0)%0A%20%20%20%20hash_obj%20%3D%20hash(obj)%0A%20%20%20%20print(f%22%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%20%7Bobj%7D%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20%7Bhash_obj%7D%22)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%20%3Cmodules.list_node.ListNode%20object%20at%200x1058fd810%3E%20%E3%81%AE%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E5%80%A4%E3%81%AF%20274267521%0A&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_hashing/hash_map.md b/ja/codes/snippets/chapter_hashing/hash_map.md index 4a2420506..e9217757e 100644 --- a/ja/codes/snippets/chapter_hashing/hash_map.md +++ b/ja/codes/snippets/chapter_hashing/hash_map.md @@ -1,72 +1,72 @@ ```python title="hash_map.py" -# ハッシュテーブルを初期化 -hmap: dict = {} +# ハッシュテーブルを初期化する +hmap = dict[int, str]() # 追加操作 -# ハッシュテーブルにペア (key, value) を追加 +# ハッシュテーブルにキーと値のペア (key, value) を追加する hmap[12836] = "小哈" hmap[15937] = "小啰" hmap[16750] = "小算" hmap[13276] = "小法" hmap[10583] = "小鸭" -# 照会操作 -# キー key を入力して値 value を取得 +# 取得操作 +# ハッシュテーブルにキー key を渡し、値 value を取得する name: str = hmap[15937] # 削除操作 -# ハッシュテーブルからペア (key, value) を削除 +# ハッシュテーブルからキーと値のペア (key, value) を削除する hmap.pop(10583) ``` ```cpp title="hash_map.cpp" -/* ハッシュテーブルを初期化 */ +/* ハッシュテーブルを初期化する */ unordered_map map; /* 追加操作 */ -// ハッシュテーブルにペア (key, value) を追加 +// ハッシュテーブルにキーと値のペア (key, value) を追加する map[12836] = "小哈"; map[15937] = "小啰"; map[16750] = "小算"; map[13276] = "小法"; map[10583] = "小鸭"; -/* 照会操作 */ -// キー key を入力して値 value を取得 +/* 取得操作 */ +// ハッシュテーブルにキー key を渡し、値 value を取得する string name = map[15937]; /* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 +// ハッシュテーブルからキーと値のペア (key, value) を削除する map.erase(10583); ``` ```java title="hash_map.java" -/* ハッシュテーブルを初期化 */ +/* ハッシュテーブルを初期化する */ Map map = new HashMap<>(); /* 追加操作 */ -// ハッシュテーブルにペア (key, value) を追加 +// ハッシュテーブルにキーと値のペア (key, value) を追加する map.put(12836, "小哈"); map.put(15937, "小啰"); map.put(16750, "小算"); map.put(13276, "小法"); map.put(10583, "小鸭"); -/* 照会操作 */ -// キー key を入力して値 value を取得 +/* 取得操作 */ +// ハッシュテーブルにキー key を渡し、値 value を取得する String name = map.get(15937); /* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 +// ハッシュテーブルからキーと値のペア (key, value) を削除する map.remove(10583); ``` ```csharp title="hash_map.cs" -/* ハッシュテーブルを初期化 */ +/* ハッシュテーブルを初期化する */ Dictionary map = new() { /* 追加操作 */ - // ハッシュテーブルにペア (key, value) を追加 + // ハッシュテーブルにキーと値のペア (key, value) を追加する { 12836, "小哈" }, { 15937, "小啰" }, { 16750, "小算" }, @@ -74,144 +74,141 @@ Dictionary map = new() { { 10583, "小鸭" } }; -/* 照会操作 */ -// キー key を入力して値 value を取得 +/* 取得操作 */ +// ハッシュテーブルにキー key を渡し、値 value を取得する string name = map[15937]; /* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 +// ハッシュテーブルからキーと値のペア (key, value) を削除する map.Remove(10583); ``` ```go title="hash_map_test.go" -/* ハッシュテーブルを初期化 */ +/* ハッシュテーブルを初期化する */ hmap := make(map[int]string) /* 追加操作 */ -// ハッシュテーブルにペア (key, value) を追加 +// ハッシュテーブルにキーと値のペア (key, value) を追加する hmap[12836] = "小哈" hmap[15937] = "小啰" hmap[16750] = "小算" hmap[13276] = "小法" hmap[10583] = "小鸭" -/* 照会操作 */ -// キー key を入力して値 value を取得 +/* 取得操作 */ +// ハッシュテーブルにキー key を渡し、値 value を取得する name := hmap[15937] /* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 +// ハッシュテーブルからキーと値のペア (key, value) を削除する delete(hmap, 10583) ``` ```swift title="hash_map.swift" -/* ハッシュテーブルを初期化 */ +/* ハッシュテーブルを初期化する */ var map: [Int: String] = [:] /* 追加操作 */ -// ハッシュテーブルにペア (key, value) を追加 +// ハッシュテーブルにキーと値のペア (key, value) を追加する map[12836] = "小哈" map[15937] = "小啰" map[16750] = "小算" map[13276] = "小法" map[10583] = "小鸭" -/* 照会操作 */ -// キー key を入力して値 value を取得 +/* 取得操作 */ +// ハッシュテーブルにキー key を渡し、値 value を取得する let name = map[15937]! /* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 +// ハッシュテーブルからキーと値のペア (key, value) を削除する map.removeValue(forKey: 10583) ``` ```javascript title="hash_map.js" -/* ハッシュテーブルを初期化 */ +/* ハッシュテーブルを初期化する */ const map = new Map(); + /* 追加操作 */ -// ハッシュテーブルにペア (key, value) を追加 +// ハッシュテーブルにキーと値のペア (key, value) を追加する map.set(12836, '小哈'); map.set(15937, '小啰'); map.set(16750, '小算'); map.set(13276, '小法'); map.set(10583, '小鸭'); -/* 照会操作 */ -// キー key を入力して値 value を取得 +/* 取得操作 */ +// ハッシュテーブルにキー key を渡し、値 value を取得する let name = map.get(15937); /* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 +// ハッシュテーブルからキーと値のペア (key, value) を削除する map.delete(10583); ``` ```typescript title="hash_map.ts" -/* ハッシュテーブルを初期化 */ +/* ハッシュテーブルを初期化する */ const map = new Map(); + /* 追加操作 */ -// ハッシュテーブルにペア (key, value) を追加 +// ハッシュテーブルにキーと値のペア (key, value) を追加する map.set(12836, '小哈'); map.set(15937, '小啰'); map.set(16750, '小算'); map.set(13276, '小法'); map.set(10583, '小鸭'); -console.info('\n追加後のハッシュテーブルは\nKey -> Value'); -console.info(map); -/* 照会操作 */ -// キー key を入力して値 value を取得 +/* 取得操作 */ +// ハッシュテーブルにキー key を渡し、値 value を取得する let name = map.get(15937); -console.info('\n学籍番号 15937 を入力して得た名前は ' + name); /* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 +// ハッシュテーブルからキーと値のペア (key, value) を削除する map.delete(10583); -console.info('\n10583 を削除した後のハッシュテーブルは\nKey -> Value'); -console.info(map); ``` ```dart title="hash_map.dart" -/* ハッシュテーブルを初期化 */ -Map map = {}; +/* ハッシュテーブルを初期化する */ +final Map map = {}; /* 追加操作 */ -// ハッシュテーブルにペア (key, value) を追加 +// ハッシュテーブルにキーと値のペア (key, value) を追加する map[12836] = "小哈"; map[15937] = "小啰"; map[16750] = "小算"; map[13276] = "小法"; map[10583] = "小鸭"; -/* 照会操作 */ -// キー key を入力して値 value を取得 -String? name = map[15937]; +/* 取得操作 */ +// ハッシュテーブルにキー key を渡し、値 value を取得する +final String? name = map[15937]; /* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 +// ハッシュテーブルからキーと値のペア (key, value) を削除する map.remove(10583); ``` ```rust title="hash_map.rs" use std::collections::HashMap; -/* ハッシュテーブルを初期化 */ -let mut map: HashMap = HashMap::new(); +// ハッシュテーブルを初期化する +let mut map = HashMap::new(); -/* 追加操作 */ -// ハッシュテーブルにペア (key, value) を追加 -map.insert(12836, "小哈".to_string()); -map.insert(15937, "小啰".to_string()); -map.insert(16750, "小算".to_string()); -map.insert(13276, "小法".to_string()); -map.insert(10583, "小鸭".to_string()); +// 追加操作 +// ハッシュテーブルにキーと値のペア (key, value) を追加する +map.insert(12836, "小哈"); +map.insert(15937, "小啰"); +map.insert(16750, "小算"); +map.insert(13276, "小法"); +map.insert(10583, "小鸭"); -/* 照会操作 */ -// キー key を入力して値 value を取得 -let _name: Option<&String> = map.get(&15937); +// 取得操作 +// ハッシュテーブルにキー key を渡し、値 value を取得する +let name = map.get(&15937).copied().unwrap(); -/* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 -let _removed_value: Option = map.remove(&10583); +// 削除操作 +// ハッシュテーブルからキーと値のペア (key, value) を削除する +_ = map.remove(&10583); ``` ```c title="hash_map.c" @@ -219,44 +216,44 @@ let _removed_value: Option = map.remove(&10583); ``` ```kotlin title="hash_map.kt" -/* ハッシュテーブルを初期化 */ -val map = HashMap() +/* ハッシュテーブルを初期化する */ +val map = HashMap() /* 追加操作 */ -// ハッシュテーブルにペア (key, value) を追加 +// ハッシュテーブルにキーと値のペア (key, value) を追加する map[12836] = "小哈" map[15937] = "小啰" map[16750] = "小算" map[13276] = "小法" map[10583] = "小鸭" -/* 照会操作 */ -// キー key を入力して値 value を取得 +/* 取得操作 */ +// ハッシュテーブルにキー key を渡し、値 value を取得する val name = map[15937] /* 削除操作 */ -// ハッシュテーブルからペア (key, value) を削除 +// ハッシュテーブルからキーと値のペア (key, value) を削除する map.remove(10583) ``` ```ruby title="hash_map.rb" -# ハッシュテーブルを初期化 +# ハッシュテーブルを初期化する hmap = {} # 追加操作 -# ハッシュテーブルにペア (key, value) を追加 +# ハッシュテーブルにキーと値のペア (key, value) を追加する hmap[12836] = "小哈" hmap[15937] = "小啰" hmap[16750] = "小算" hmap[13276] = "小法" hmap[10583] = "小鸭" -# 照会操作 -# キー key を入力して値 value を取得 +# 取得操作 +# ハッシュテーブルにキー key を渡し、値 value を取得する name = hmap[15937] # 削除操作 -# ハッシュテーブルからペア (key, value) を削除 +# ハッシュテーブルからキーと値のペア (key, value) を削除する hmap.delete(10583) ``` @@ -265,157 +262,166 @@ https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3 ```python title="hash_map.py" -# ハッシュテーブルを走査 -# キーと値のペアを走査 key->value +# ハッシュテーブルを走査する +# キーと値のペア key->value を走査する for key, value in hmap.items(): print(key, "->", value) -# キーだけを走査 key + +# キー key だけを走査する for key in hmap.keys(): print(key) -# 値だけを走査 value -for value in hmap.values(): - print(value) + +# 値 value だけを走査する +for val in hmap.values(): + print(val) ``` ```cpp title="hash_map.cpp" -/* ハッシュテーブルを走査 */ -// キーと値のペアを走査 key->value -for (auto kv: map) { +/* ハッシュテーブルを走査する */ +// キーと値のペア key->value を走査する +for (auto kv : map) { cout << kv.first << " -> " << kv.second << endl; } -// イテレータで走査 key->value + +// イテレータで key->value を走査する for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; + cout << iter->first << " -> " << iter->second << endl; } ``` ```java title="hash_map.java" -/* ハッシュテーブルを走査 */ -// キーと値のペアを走査 key->value -for (Map.Entry kv: map.entrySet()) { +/* ハッシュテーブルを走査する */ +// キーと値のペア key->value を走査する +for (Map.Entry kv : map.entrySet()) { System.out.println(kv.getKey() + " -> " + kv.getValue()); } -// キーだけを走査 key -for (int key: map.keySet()) { + +// キー key だけを走査する +for (int key : map.keySet()) { System.out.println(key); } -// 値だけを走査 value -for (String val: map.values()) { + +// 値 value だけを走査する +for (String val : map.values()) { System.out.println(val); } ``` ```csharp title="hash_map.cs" -/* ハッシュテーブルを走査 */ -// キーと値のペアを走査 Key->Value +/* ハッシュテーブルを走査する */ +// キーと値のペア key->value を走査する foreach (var kv in map) { Console.WriteLine(kv.Key + " -> " + kv.Value); } -// キーだけを走査 key + +// キー key だけを走査する foreach (int key in map.Keys) { Console.WriteLine(key); } -// 値だけを走査 value + +// 値 value だけを走査する foreach (string val in map.Values) { Console.WriteLine(val); } ``` ```go title="hash_map_test.go" -/* ハッシュテーブルを走査 */ -// キーと値のペアを走査 key->value +/* ハッシュテーブルを走査する */ +// キーと値のペア key->value を走査する for key, value := range hmap { fmt.Println(key, "->", value) } -// キーだけを走査 key + +// キー key だけを走査する for key := range hmap { fmt.Println(key) } -// 値だけを走査 value + +// 値 value だけを走査する for _, value := range hmap { fmt.Println(value) } ``` ```swift title="hash_map.swift" -/* ハッシュテーブルを走査 */ -// キーと値のペアを走査 Key->Value +/* ハッシュテーブルを走査する */ +// キーと値のペア key->value を走査する for (key, value) in map { print("\(key) -> \(value)") } -// キーだけを走査 Key + +// キー key だけを走査する for key in map.keys { print(key) } -// 値だけを走査 Value + +// 値 value だけを走査する for value in map.values { print(value) } ``` ```javascript title="hash_map.js" -/* ハッシュテーブルを走査 */ -console.info('\nキーと値のペアを走査 Key->Value'); +/* ハッシュテーブルを走査する */ +// キーと値のペア key->value を走査する for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\nキーだけを走査 Key'); + +// キー key だけを走査する for (const k of map.keys()) { console.info(k); } -console.info('\n値だけを走査 Value'); + +// 値 value だけを走査する for (const v of map.values()) { console.info(v); } ``` ```typescript title="hash_map.ts" -/* ハッシュテーブルを走査 */ -console.info('\nキーと値のペアを走査 Key->Value'); +/* ハッシュテーブルを走査する */ +// キーと値のペア key->value を走査する for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\nキーだけを走査 Key'); + +// キー key だけを走査する for (const k of map.keys()) { console.info(k); } -console.info('\n値だけを走査 Value'); + +// 値 value だけを走査する for (const v of map.values()) { console.info(v); } ``` ```dart title="hash_map.dart" -/* ハッシュテーブルを走査 */ -// キーと値のペアを走査 Key->Value -map.forEach((key, value) { - print('$key -> $value'); -}); +/* ハッシュテーブルを走査する */ +// キーと値のペア key->value を走査する +map.forEach((key, value) => print("$key -> $value")); -// キーだけを走査 Key -map.keys.forEach((key) { - print(key); -}); +// キー key だけを走査する +map.keys.forEach((key) => print(key)); -// 値だけを走査 Value -map.values.forEach((value) { - print(value); -}); +// 値 value だけを走査する +map.values.forEach((value) => print(value)); ``` ```rust title="hash_map.rs" -/* ハッシュテーブルを走査 */ -// キーと値のペアを走査 Key->Value +// ハッシュテーブルを走査する +// キーと値のペア key->value を走査する for (key, value) in &map { println!("{key} -> {value}"); } -// キーだけを走査 Key +// キー key だけを走査する for key in map.keys() { println!("{key}"); } -// 値だけを走査 Value +// 値 value だけを走査する for value in map.values() { println!("{value}"); } @@ -426,32 +432,34 @@ for value in map.values() { ``` ```kotlin title="hash_map.kt" -/* ハッシュテーブルを走査 */ -// キーと値のペアを走査 key->value +/* ハッシュテーブルを走査する */ +// キーと値のペア key->value を走査する for ((key, value) in map) { println("$key -> $value") } -// キーだけを走査 key + +// キー key だけを走査する for (key in map.keys) { println(key) } -// 値だけを走査 value + +// 値 value だけを走査する for (_val in map.values) { println(_val) } ``` ```ruby title="hash_map.rb" -# ハッシュテーブルを走査 -# キーと値のペアを走査 key->value +# ハッシュテーブルを走査する +# キーと値のペア key->value を走査する hmap.entries.each { |key, value| puts "#{key} -> #{value}" } -# キーだけを走査 key +# キー key だけを走査する hmap.keys.each { |key| puts key } -# 値だけを走査 value +# 値 value だけを走査する hmap.values.each { |val| puts val } ``` -https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BF%BD%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%81%AB%E3%83%9A%E3%82%A2%20(key%2C%20value)%20%E3%82%92%E8%BF%BD%E5%8A%A0%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E8%B5%B0%E6%9F%BB%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%E3%81%A8%E5%80%A4%E3%81%AE%E3%83%9A%E3%82%A2%E3%82%92%E8%B5%B0%E6%9F%BB%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items()%3A%0A%20%20%20%20%20%20%20%20print(key%2C%20%22-%3E%22%2C%20value)%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%E3%81%A0%E3%81%91%E3%82%92%E8%B5%B0%E6%9F%BB%20key%0A%20%20%20%20for%20key%20in%20hmap.keys()%3A%0A%20%20%20%20%20%20%20%20print(key)%0A%20%20%20%20%23%20%E5%80%A4%E3%81%A0%E3%81%91%E3%82%92%E8%B5%B0%E6%9F%BB%20value%0A%20%20%20%20for%20value%20in%20hmap.values()%3A%0A%20%20%20%20%20%20%20%20print(value)&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BF%BD%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%81%AB%E3%83%9A%E3%82%A2%20(key%2C%20value)%20%E3%82%92%E8%BF%BD%E5%8A%A0%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB%E3%82%92%E8%B5%B0%E6%9F%BB%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%E3%81%A8%E5%80%A4%E3%81%AE%E3%83%9A%E3%82%A2%E3%82%92%E8%B5%B0%E6%9F%BB%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items()%3A%0A%20%20%20%20%20%20%20%20print(key%2C%20%22-%3E%22%2C%20value)%0A%20%20%20%20%23%20%E3%82%AD%E3%83%BC%E3%81%A0%E3%81%91%E3%82%92%E8%B5%B0%E6%9F%BB%20key%0A%20%20%20%20for%20key%20in%20hmap.keys()%3A%0A%20%20%20%20%20%20%20%20print(key)%0A%20%20%20%20%23%20%E5%80%A4%E3%81%A0%E3%81%91%E3%82%92%E8%B5%B0%E6%9F%BB%20value%0A%20%20%20%20for%20val%20in%20hmap.values()%3A%0A%20%20%20%20%20%20%20%20print(val)&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_heap/heap.md b/ja/codes/snippets/chapter_heap/heap.md index 511d7b632..2e7925cde 100644 --- a/ja/codes/snippets/chapter_heap/heap.md +++ b/ja/codes/snippets/chapter_heap/heap.md @@ -1,162 +1,166 @@ ```python title="heap.py" -# 最小ヒープを初期化 +# 最小ヒープを初期化する min_heap, flag = [], 1 -# 最大ヒープを初期化 +# 最大ヒープを初期化する max_heap, flag = [], -1 -# Python の heapq モジュールはデフォルトで最小ヒープを実装する -# 要素の符号を反転してから挿入すると、大小関係が逆転し最大ヒープを実現できる +# Python の heapq モジュールは既定で最小ヒープを実装する +# 「要素の符号を反転」してからヒープに挿入すれば、大小関係が逆転し、最大ヒープを実装できる # この例では flag = 1 が最小ヒープ、flag = -1 が最大ヒープに対応する -# 要素をヒープに挿入 +# ヒープに要素を挿入する heapq.heappush(max_heap, flag * 1) heapq.heappush(max_heap, flag * 3) heapq.heappush(max_heap, flag * 2) heapq.heappush(max_heap, flag * 5) heapq.heappush(max_heap, flag * 4) -# ヒープの先頭要素を取得 -peek: int = flag * max_heap[0] # 5 +# ヒープの先頭要素を取得する +peek: int = flag * max_heap[0] # 5 # ヒープの先頭要素を取り出す -# 取り出した要素は降順の列になる -val = flag * heapq.heappop(max_heap) # 5 -val = flag * heapq.heappop(max_heap) # 4 -val = flag * heapq.heappop(max_heap) # 3 -val = flag * heapq.heappop(max_heap) # 2 -val = flag * heapq.heappop(max_heap) # 1 +# 取り出した要素は降順の列を形成する +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 -# ヒープの要素数を取得 +# ヒープのサイズを取得する size: int = len(max_heap) -# ヒープが空かどうかを判定 +# ヒープが空か判定 is_empty: bool = not max_heap -# リストを入力してヒープを構築 +# リストを入力してヒープを構築する +# 時間計算量は O(n) であり、O(nlogn) ではない min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) ``` ```cpp title="heap.cpp" -/* ヒープを初期化 */ -// 最小ヒープを初期化 +/* ヒープを初期化する */ +// 最小ヒープを初期化する priority_queue, greater> minHeap; -// 最大ヒープを初期化 +// 最大ヒープを初期化する priority_queue, less> maxHeap; -/* 要素をヒープに挿入 */ +/* ヒープに要素を挿入する */ maxHeap.push(1); maxHeap.push(3); maxHeap.push(2); maxHeap.push(5); maxHeap.push(4); -/* ヒープの先頭要素を取得 */ +/* ヒープの先頭要素を取得する */ int peek = maxHeap.top(); // 5 /* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる +// 取り出した要素は降順の列を形成する maxHeap.pop(); // 5 maxHeap.pop(); // 4 maxHeap.pop(); // 3 maxHeap.pop(); // 2 maxHeap.pop(); // 1 -/* ヒープの要素数を取得 */ +/* ヒープのサイズを取得する */ int size = maxHeap.size(); -/* ヒープが空かどうかを判定 */ +/* ヒープが空か判定 */ bool isEmpty = maxHeap.empty(); -/* リストを入力してヒープを構築 */ +/* リストを入力してヒープを構築する */ +// 時間計算量は O(n) であり、O(nlogn) ではない vector input{1, 3, 2, 5, 4}; minHeap = priority_queue, greater>(input.begin(), input.end()); ``` ```java title="heap.java" -/* ヒープを初期化 */ -// 最小ヒープを初期化 +/* ヒープを初期化する */ +// 最小ヒープを初期化する Queue minHeap = new PriorityQueue<>(); -// 最大ヒープを初期化(ラムダ式で Comparator を変更する) +// 最大ヒープを初期化する(ラムダ式で Comparator を変更すればよい) Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); -/* 要素をヒープに挿入 */ +/* ヒープに要素を挿入する */ maxHeap.offer(1); maxHeap.offer(3); maxHeap.offer(2); maxHeap.offer(5); maxHeap.offer(4); -/* ヒープの先頭要素を取得 */ +/* ヒープの先頭要素を取得する */ int peek = maxHeap.peek(); // 5 /* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる +// 取り出した要素は降順の列を形成する peek = maxHeap.poll(); // 5 peek = maxHeap.poll(); // 4 peek = maxHeap.poll(); // 3 peek = maxHeap.poll(); // 2 peek = maxHeap.poll(); // 1 -/* ヒープの要素数を取得 */ +/* ヒープのサイズを取得する */ int size = maxHeap.size(); -/* ヒープが空かどうかを判定 */ +/* ヒープが空か判定 */ boolean isEmpty = maxHeap.isEmpty(); -/* リストを入力してヒープを構築 */ +/* リストを入力してヒープを構築する */ +// 時間計算量は O(n) であり、O(nlogn) ではない minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); ``` ```csharp title="heap.cs" -/* ヒープを初期化 */ -// 最小ヒープを初期化 +/* ヒープを初期化する */ +// 最小ヒープを初期化する PriorityQueue minHeap = new(); -// 最大ヒープを初期化(ラムダ式で Comparer を変更する) +// 最大ヒープを初期化する(ラムダ式で Comparer を変更すればよい) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); -/* 要素をヒープに挿入 */ +/* ヒープに要素を挿入する */ maxHeap.Enqueue(1, 1); maxHeap.Enqueue(3, 3); maxHeap.Enqueue(2, 2); maxHeap.Enqueue(5, 5); maxHeap.Enqueue(4, 4); -/* ヒープの先頭要素を取得 */ -int peek = maxHeap.Peek();//5 +/* ヒープの先頭要素を取得する */ +int peek = maxHeap.Peek(); // 5 /* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +// 取り出した要素は降順の列を形成する +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 -/* ヒープの要素数を取得 */ +/* ヒープのサイズを取得する */ int size = maxHeap.Count; -/* ヒープが空かどうかを判定 */ +/* ヒープが空か判定 */ bool isEmpty = maxHeap.Count == 0; -/* リストを入力してヒープを構築 */ +/* リストを入力してヒープを構築する */ +// 時間計算量は O(n) であり、O(nlogn) ではない minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); ``` ```go title="heap.go" // Go では heap.Interface を実装して整数の最大ヒープを構築できる -// heap.Interface の実装には sort.Interface の実装も必要 +// heap.Interface の実装には sort.Interface も実装する必要がある type intHeap []any -// Push は heap.Interface のメソッドで、ヒープへの挿入を実装する +// Push は heap.Interface の関数であり、ヒープへの要素の挿入を実装する func (h *intHeap) Push(x any) { - // Push と Pop はポインタレシーバーを引数として使う - // スライスの内容だけでなく長さも変更するため + // Push と Pop は引数としてポインタレシーバを使う + // スライスの内容を変更するだけでなく、スライスの長さも変更するためである。 *h = append(*h, x.(int)) } -// Pop は heap.Interface のメソッドで、先頭要素の取り出しを実装する +// Pop は heap.Interface の関数であり、ヒープの先頭要素の取り出しを実装する func (h *intHeap) Pop() any { // 取り出す要素は末尾に格納されている last := (*h)[len(*h)-1] @@ -164,77 +168,79 @@ func (h *intHeap) Pop() any { return last } -// Len は sort.Interface のメソッド +// Len は sort.Interface の関数 func (h *intHeap) Len() int { return len(*h) } -// Less は sort.Interface のメソッド +// Less は sort.Interface の関数 func (h *intHeap) Less(i, j int) bool { - // 最小ヒープを実装する場合は、小なり記号に変更する + // 最小ヒープを実装する場合、不等号を小なりに変更する必要がある return (*h)[i].(int) > (*h)[j].(int) } -// Swap は sort.Interface のメソッド +// Swap は sort.Interface の関数 func (h *intHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } -// Top ヒープの先頭要素を取得 +// Top はヒープの先頭要素を取得する func (h *intHeap) Top() any { return (*h)[0] } -/* 実行用コード */ func TestHeap(t *testing.T) { - /* ヒープを初期化 */ - // 最大ヒープを初期化 + /* ヒープを初期化する */ + // 最大ヒープを初期化する maxHeap := &intHeap{} heap.Init(maxHeap) - /* 要素をヒープに挿入 */ - // heap.Interface のメソッドを呼んで要素を追加 + /* ヒープに要素を挿入する */ + // heap.Interface の関数を呼び出し、要素を追加する heap.Push(maxHeap, 1) heap.Push(maxHeap, 3) heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) - /* ヒープの先頭要素を取得 */ + /* ヒープの先頭要素を取得する */ top := maxHeap.Top() fmt.Printf("ヒープの先頭要素は %d\n", top) /* ヒープの先頭要素を取り出す */ - // heap.Interface のメソッドを呼んで要素を削除 - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 + // heap.Interface の関数を呼び出し、要素を取り除く + fmt.Printf("ヒープから取り出した要素は %d\n", heap.Pop(maxHeap)) // 5 + fmt.Printf("ヒープから取り出した要素は %d\n", heap.Pop(maxHeap)) // 4 + fmt.Printf("ヒープから取り出した要素は %d\n", heap.Pop(maxHeap)) // 3 + fmt.Printf("ヒープから取り出した要素は %d\n", heap.Pop(maxHeap)) // 2 + fmt.Printf("ヒープから取り出した要素は %d\n", heap.Pop(maxHeap)) // 1 - /* ヒープの要素数を取得 */ + /* ヒープのサイズを取得する */ size := len(*maxHeap) fmt.Printf("ヒープの要素数は %d\n", size) - /* ヒープが空かどうかを判定 */ + /* ヒープが空か判定 */ isEmpty := len(*maxHeap) == 0 fmt.Printf("ヒープは空か %t\n", isEmpty) } ``` ```swift title="heap.swift" -/* ヒープを初期化 */ -// Swift の Heap 型は最大ヒープと最小ヒープの両方に対応し、swift-collections の導入が必要 +import HeapModule + +/* ヒープを初期化する */ +// Swift の Heap 型は最大ヒープと最小ヒープの両方に対応し、swift-collections パッケージを導入する必要がある var heap = Heap() -/* 要素をヒープに挿入 */ +/* ヒープに要素を挿入する */ heap.insert(1) heap.insert(3) heap.insert(2) heap.insert(5) heap.insert(4) -/* ヒープの先頭要素を取得 */ -var peek = heap.max()! +/* ヒープの先頭要素を取得する */ +var peek = heap.max() /* ヒープの先頭要素を取り出す */ peek = heap.removeMax() // 5 @@ -243,13 +249,14 @@ peek = heap.removeMax() // 3 peek = heap.removeMax() // 2 peek = heap.removeMax() // 1 -/* ヒープの要素数を取得 */ +/* ヒープのサイズを取得する */ let size = heap.count -/* ヒープが空かどうかを判定 */ +/* ヒープが空か判定 */ let isEmpty = heap.isEmpty -/* リストを入力してヒープを構築 */ +/* リストを入力してヒープを構築する */ +// 時間計算量は O(n) であり、O(nlogn) ではない let heap2 = Heap([1, 3, 2, 5, 4]) ``` @@ -266,41 +273,43 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +use std::{cmp::Reverse, collections::BinaryHeap}; -/* ヒープを初期化 */ -// 最小ヒープを初期化 -let mut min_heap = BinaryHeap::>::new(); -// 最大ヒープを初期化 +/* ヒープを初期化する */ +// 最小ヒープを初期化する +// Rust の BinaryHeap は最大ヒープであり、最小ヒープにするには要素を Reverse で包む必要がある +#[allow(unused_assignments)] +let mut min_heap = BinaryHeap::new(); +// 最大ヒープを初期化する let mut max_heap = BinaryHeap::new(); -/* 要素をヒープに挿入 */ +/* ヒープに要素を挿入する */ max_heap.push(1); max_heap.push(3); max_heap.push(2); max_heap.push(5); max_heap.push(4); -/* ヒープの先頭要素を取得 */ -let peek = max_heap.peek().unwrap(); // 5 +/* ヒープの先頭要素を取得する */ +let peek = max_heap.peek().unwrap(); // 5 /* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる -let peek = max_heap.pop().unwrap(); // 5 -let peek = max_heap.pop().unwrap(); // 4 -let peek = max_heap.pop().unwrap(); // 3 -let peek = max_heap.pop().unwrap(); // 2 -let peek = max_heap.pop().unwrap(); // 1 +// 取り出した要素は降順の列を形成する +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 -/* ヒープの要素数を取得 */ +/* ヒープのサイズを取得する */ let size = max_heap.len(); -/* ヒープが空かどうかを判定 */ +/* ヒープが空か判定 */ let is_empty = max_heap.is_empty(); -/* リストを入力してヒープを構築 */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +/* リストを入力してヒープを構築する */ +// 時間計算量は O(n) であり、O(nlogn) ではない +min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); ``` ```c title="heap.c" @@ -308,38 +317,39 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse ``` ```kotlin title="heap.kt" -/* ヒープを初期化 */ -// 最小ヒープを初期化 +/* ヒープを初期化する */ +// 最小ヒープを初期化する var minHeap = PriorityQueue() -// 最大ヒープを初期化(ラムダ式で Comparator を変更する) +// 最大ヒープを初期化する(ラムダ式で Comparator を変更すればよい) val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } -/* 要素をヒープに挿入 */ +/* ヒープに要素を挿入する */ maxHeap.offer(1) maxHeap.offer(3) maxHeap.offer(2) maxHeap.offer(5) maxHeap.offer(4) -/* ヒープの先頭要素を取得 */ +/* ヒープの先頭要素を取得する */ var peek = maxHeap.peek() // 5 /* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる +// 取り出した要素は降順の列を形成する peek = maxHeap.poll() // 5 peek = maxHeap.poll() // 4 peek = maxHeap.poll() // 3 peek = maxHeap.poll() // 2 peek = maxHeap.poll() // 1 -/* ヒープの要素数を取得 */ +/* ヒープのサイズを取得する */ val size = maxHeap.size -/* ヒープが空かどうかを判定 */ +/* ヒープが空か判定 */ val isEmpty = maxHeap.isEmpty() -/* リストを入力してヒープを構築 */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +/* リストを入力してヒープを構築する */ +// 時間計算量は O(n) であり、O(nlogn) ではない +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` ```ruby title="heap.rb" @@ -347,4 +357,4 @@ minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` -https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E3%81%AE%20heapq%20%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AF%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88%E3%81%A7%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%AE%9F%E8%A3%85%E3%81%99%E3%82%8B%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AE%E7%AC%A6%E5%8F%B7%E3%82%92%E5%8F%8D%E8%BB%A2%E3%81%97%E3%81%A6%E3%81%8B%E3%82%89%E6%8C%BF%E5%85%A5%E3%81%99%E3%82%8B%E3%81%A8%E3%80%81%E5%A4%A7%E5%B0%8F%E9%96%A2%E4%BF%82%E3%81%8C%E9%80%86%E8%BB%A2%E3%81%97%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%AE%9F%E7%8F%BE%E3%81%A7%E3%81%8D%E3%82%8B%0A%20%20%20%20%23%20%E3%81%93%E3%81%AE%E4%BE%8B%E3%81%A7%E3%81%AF%20flag%20%3D%201%20%E3%81%8C%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%80%81flag%20%3D%20-1%20%E3%81%8C%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%81%AB%E5%AF%BE%E5%BF%9C%E3%81%99%E3%82%8B%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%92%E3%83%BC%E3%83%97%E3%81%AB%E6%8C%BF%E5%85%A5%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%201)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%203)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%202)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%205)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%204)%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20peek%20%3D%20flag%20*%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%99%0A%20%20%20%20%23%20%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%E3%81%AF%E9%99%8D%E9%A0%86%E3%81%AE%E5%88%97%E3%81%AB%E3%81%AA%E3%82%8B%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%205%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%204%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%203%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%202%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E8%A6%81%E7%B4%A0%E6%95%B0%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(max_heap)%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%8C%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%85%A5%E5%8A%9B%E3%81%97%E3%81%A6%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E6%A7%8B%E7%AF%89%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify(min_heap)&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E3%81%AE%20heapq%20%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AF%E3%83%87%E3%83%95%E3%82%A9%E3%83%AB%E3%83%88%E3%81%A7%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%AE%9F%E8%A3%85%E3%81%99%E3%82%8B%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%81%AE%E7%AC%A6%E5%8F%B7%E3%82%92%E5%8F%8D%E8%BB%A2%E3%81%97%E3%81%A6%E3%81%8B%E3%82%89%E6%8C%BF%E5%85%A5%E3%81%99%E3%82%8B%E3%81%A8%E3%80%81%E5%A4%A7%E5%B0%8F%E9%96%A2%E4%BF%82%E3%81%8C%E9%80%86%E8%BB%A2%E3%81%97%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E5%AE%9F%E7%8F%BE%E3%81%A7%E3%81%8D%E3%82%8B%0A%20%20%20%20%23%20%E3%81%93%E3%81%AE%E4%BE%8B%E3%81%A7%E3%81%AF%20flag%20%3D%201%20%E3%81%8C%E6%9C%80%E5%B0%8F%E3%83%92%E3%83%BC%E3%83%97%E3%80%81flag%20%3D%20-1%20%E3%81%8C%E6%9C%80%E5%A4%A7%E3%83%92%E3%83%BC%E3%83%97%E3%81%AB%E5%AF%BE%E5%BF%9C%E3%81%99%E3%82%8B%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%A6%81%E7%B4%A0%E3%82%92%E3%83%92%E3%83%BC%E3%83%97%E3%81%AB%E6%8C%BF%E5%85%A5%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%201)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%203)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%202)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%205)%0A%20%20%20%20heapq.heappush(max_heap%2C%20flag%20*%204)%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20peek%20%3D%20flag%20*%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E5%85%88%E9%A0%AD%E8%A6%81%E7%B4%A0%E3%82%92%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%99%0A%20%20%20%20%23%20%E5%8F%96%E3%82%8A%E5%87%BA%E3%81%97%E3%81%9F%E8%A6%81%E7%B4%A0%E3%81%AF%E9%99%8D%E9%A0%86%E3%81%AE%E5%88%97%E3%81%AB%E3%81%AA%E3%82%8B%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%205%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%204%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%203%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%202%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop(max_heap)%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%AE%E8%A6%81%E7%B4%A0%E6%95%B0%E3%82%92%E5%8F%96%E5%BE%97%0A%20%20%20%20size%20%3D%20len(max_heap)%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%92%E3%83%BC%E3%83%97%E3%81%8C%E7%A9%BA%E3%81%8B%E3%81%A9%E3%81%86%E3%81%8B%E3%82%92%E5%88%A4%E5%AE%9A%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E3%83%AA%E3%82%B9%E3%83%88%E3%82%92%E5%85%A5%E5%8A%9B%E3%81%97%E3%81%A6%E3%83%92%E3%83%BC%E3%83%97%E3%82%92%E6%A7%8B%E7%AF%89%0A%20%20%20%20%23%20%E6%99%82%E9%96%93%E8%A8%88%E7%AE%97%E9%87%8F%E3%81%AF%20O(n)%20%E3%81%A7%E3%81%82%E3%82%8A%E3%80%81O(nlogn)%20%E3%81%A7%E3%81%AF%E3%81%AA%E3%81%84%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify(min_heap)&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/snippets/chapter_stack_and_queue/deque.md b/ja/codes/snippets/chapter_stack_and_queue/deque.md index 15056280a..56a80a38f 100644 --- a/ja/codes/snippets/chapter_stack_and_queue/deque.md +++ b/ja/codes/snippets/chapter_stack_and_queue/deque.md @@ -2,277 +2,273 @@ ```python title="deque.py" from collections import deque -# 両端キューを初期化 +# 両端キューを初期化する deq: deque[int] = deque() -# 要素をエンキュー -deq.append(2) # 末尾に追加 +# 要素をエンキューする +deq.append(2) # キューの末尾に追加する deq.append(5) deq.append(4) -deq.appendleft(3) # 先頭に追加 +deq.appendleft(3) # キューの先頭に追加する deq.appendleft(1) -# 要素にアクセス -front: int = deq[0] # 先頭要素 -rear: int = deq[-1] # 末尾要素 +# 要素にアクセスする +front: int = deq[0] # キューの先頭要素 +rear: int = deq[-1] # キューの末尾要素 -# 要素をデキュー -pop_front: int = deq.popleft() # 先頭要素を取り出す -pop_rear: int = deq.pop() # 末尾要素を取り出す +# 要素をデキューする +pop_front: int = deq.popleft() # キューの先頭要素をデキューする +pop_rear: int = deq.pop() # キューの末尾要素をデキューする -# 両端キューの長さを取得 +# 両端キューの長さを取得する size: int = len(deq) -# 両端キューが空かどうかを判定 +# 両端キューが空かどうかを判定する is_empty: bool = len(deq) == 0 ``` ```cpp title="deque.cpp" -/* 両端キューを初期化 */ +/* 両端キューを初期化する */ deque deque; -/* 要素をエンキュー */ -deque.push_back(2); // 末尾に追加 +/* 要素をエンキューする */ +deque.push_back(2); // キューの末尾に追加する deque.push_back(5); deque.push_back(4); -deque.push_front(3); // 先頭に追加 +deque.push_front(3); // キューの先頭に追加する deque.push_front(1); -/* 要素にアクセス */ -int front = deque.front(); // 先頭要素 -int back = deque.back(); // 末尾要素 +/* 要素にアクセスする */ +int front = deque.front(); // キューの先頭要素 +int back = deque.back(); // キューの末尾要素 -/* 要素をデキュー */ -deque.pop_front(); // 先頭要素を取り出す -deque.pop_back(); // 末尾要素を取り出す +/* 要素をデキューする */ +deque.pop_front(); // キューの先頭要素をデキューする +deque.pop_back(); // キューの末尾要素をデキューする -/* 両端キューの長さを取得 */ +/* 両端キューの長さを取得する */ int size = deque.size(); -/* 両端キューが空かどうかを判定 */ +/* 両端キューが空かどうかを判定する */ bool empty = deque.empty(); ``` ```java title="deque.java" -/* 両端キューを初期化 */ +/* 両端キューを初期化する */ Deque deque = new LinkedList<>(); -/* 要素をエンキュー */ -deque.offerLast(2); // 末尾に追加 +/* 要素をエンキューする */ +deque.offerLast(2); // キューの末尾に追加する deque.offerLast(5); deque.offerLast(4); -deque.offerFirst(3); // 先頭に追加 +deque.offerFirst(3); // キューの先頭に追加する deque.offerFirst(1); -/* 要素にアクセス */ -int peekFirst = deque.peekFirst(); // 先頭要素 -int peekLast = deque.peekLast(); // 末尾要素 +/* 要素にアクセスする */ +int peekFirst = deque.peekFirst(); // キューの先頭要素 +int peekLast = deque.peekLast(); // キューの末尾要素 -/* 要素をデキュー */ -int popFirst = deque.pollFirst(); // 先頭要素を取り出す -int popLast = deque.pollLast(); // 末尾要素を取り出す +/* 要素をデキューする */ +int popFirst = deque.pollFirst(); // キューの先頭要素をデキューする +int popLast = deque.pollLast(); // キューの末尾要素をデキューする -/* 両端キューの長さを取得 */ +/* 両端キューの長さを取得する */ int size = deque.size(); -/* 両端キューが空かどうかを判定 */ +/* 両端キューが空かどうかを判定する */ boolean isEmpty = deque.isEmpty(); ``` ```csharp title="deque.cs" -/* 両端キューを初期化 */ -// C# では LinkedList を両端キューとして使う +/* 両端キューを初期化する */ +// C# では、連結リスト LinkedList を両端キューとして使う LinkedList deque = new(); -/* 要素をエンキュー */ -deque.AddLast(2); // 末尾に追加 +/* 要素をエンキューする */ +deque.AddLast(2); // キューの末尾に追加する deque.AddLast(5); deque.AddLast(4); -deque.AddFirst(3); // 先頭に追加 +deque.AddFirst(3); // キューの先頭に追加する deque.AddFirst(1); -/* 要素にアクセス */ -int peekFirst = deque.First.Value; // 先頭要素 -int peekLast = deque.Last.Value; // 末尾要素 +/* 要素にアクセスする */ +int? peekFirst = deque.First?.Value; // キューの先頭要素 +int? peekLast = deque.Last?.Value; // キューの末尾要素 -/* 要素をデキュー */ -deque.RemoveFirst(); // 先頭要素を取り出す -deque.RemoveLast(); // 末尾要素を取り出す +/* 要素をデキューする */ +deque.RemoveFirst(); // キューの先頭要素をデキューする +deque.RemoveLast(); // キューの末尾要素をデキューする -/* 両端キューの長さを取得 */ +/* 両端キューの長さを取得する */ int size = deque.Count; -/* 両端キューが空かどうかを判定 */ +/* 両端キューが空かどうかを判定する */ bool isEmpty = deque.Count == 0; ``` ```go title="deque_test.go" -/* 両端キューを初期化 */ +/* 両端キューを初期化する */ // Go では list を両端キューとして使う deque := list.New() -/* 要素をエンキュー */ -deque.PushBack(2) // 末尾に追加 +/* 要素をエンキューする */ +deque.PushBack(2) // キューの末尾に追加する deque.PushBack(5) deque.PushBack(4) -deque.PushFront(3) // 先頭に追加 +deque.PushFront(3) // キューの先頭に追加する deque.PushFront(1) -/* 要素にアクセス */ -front := deque.Front() // 先頭要素 -rear := deque.Back() // 末尾要素 +/* 要素にアクセスする */ +front := deque.Front() // キューの先頭要素 +rear := deque.Back() // キューの末尾要素 -/* 要素をデキュー */ -deque.Remove(front) // 先頭要素を取り出す -deque.Remove(rear) // 末尾要素を取り出す +/* 要素をデキューする */ +deque.Remove(front) // キューの先頭要素をデキューする +deque.Remove(rear) // キューの末尾要素をデキューする -/* 両端キューの長さを取得 */ +/* 両端キューの長さを取得する */ size := deque.Len() -/* 両端キューが空かどうかを判定 */ +/* 両端キューが空かどうかを判定する */ isEmpty := deque.Len() == 0 ``` ```swift title="deque.swift" -/* 両端キューを初期化 */ +/* 両端キューを初期化する */ // Swift には組み込みの両端キュークラスがないため、Array を両端キューとして使える var deque: [Int] = [] -/* 要素をエンキュー */ -deque.append(2) // 末尾に追加 +/* 要素をエンキューする */ +deque.append(2) // キューの末尾に追加する deque.append(5) deque.append(4) -deque.insert(3, at: 0) // 先頭に追加 +deque.insert(3, at: 0) // キューの先頭に追加する deque.insert(1, at: 0) -/* 要素にアクセス */ -let peekFirst = deque.first! // 先頭要素 -let peekLast = deque.last! // 末尾要素 +/* 要素にアクセスする */ +let peekFirst = deque.first! // キューの先頭要素 +let peekLast = deque.last! // キューの末尾要素 -/* 要素をデキュー */ -// Array で代用する場合、popFirst の計算量は O(n) -let popFirst = deque.removeFirst() // 先頭要素を取り出す -let popLast = deque.removeLast() // 末尾要素を取り出す +/* 要素をデキューする */ +// Array で再現する場合、removeFirst の計算量は O(n) +let popFirst = deque.removeFirst() // キューの先頭要素をデキューする +let popLast = deque.removeLast() // キューの末尾要素をデキューする -/* 両端キューの長さを取得 */ +/* 両端キューの長さを取得する */ let size = deque.count -/* 両端キューが空かどうかを判定 */ +/* 両端キューが空かどうかを判定する */ let isEmpty = deque.isEmpty ``` ```javascript title="deque.js" -/* 両端キューを初期化 */ -// JavaScript には組み込みの両端キューがないため、Array で代用する必要がある +/* 両端キューを初期化する */ +// JavaScript には組み込みの両端キューがないため、Array を両端キューとして使うしかない const deque = []; -/* 要素をエンキュー */ +/* 要素をエンキューする */ deque.push(2); deque.push(5); deque.push(4); -// 配列なので unshift() の時間計算量は O(n) であることに注意 +// 配列なので unshift() メソッドの時間計算量は O(n) であることに注意 deque.unshift(3); deque.unshift(1); -/* 要素にアクセス */ +/* 要素にアクセスする */ const peekFirst = deque[0]; const peekLast = deque[deque.length - 1]; -/* 要素をデキュー */ -// 配列なので shift() の時間計算量は O(n) であることに注意 +/* 要素をデキューする */ +// 配列なので shift() メソッドの時間計算量は O(n) であることに注意 const popFront = deque.shift(); const popBack = deque.pop(); -/* 両端キューの長さを取得 */ +/* 両端キューの長さを取得する */ const size = deque.length; -/* 両端キューが空かどうかを判定 */ +/* 両端キューが空かどうかを判定する */ const isEmpty = size === 0; ``` ```typescript title="deque.ts" -/* 両端キューを初期化 */ -// TypeScript には組み込みの両端キューがないため、Array で代用する必要がある +/* 両端キューを初期化する */ +// TypeScript には組み込みの両端キューがないため、Array を両端キューとして使うしかない const deque: number[] = []; -/* 要素をエンキュー */ +/* 要素をエンキューする */ deque.push(2); deque.push(5); deque.push(4); -// 配列なので unshift() の時間計算量は O(n) であることに注意 +// 配列なので unshift() メソッドの時間計算量は O(n) であることに注意 deque.unshift(3); deque.unshift(1); -/* 要素にアクセス */ +/* 要素にアクセスする */ const peekFirst: number = deque[0]; const peekLast: number = deque[deque.length - 1]; -/* 要素をデキュー */ -// 配列なので shift() の時間計算量は O(n) であることに注意 +/* 要素をデキューする */ +// 配列なので shift() メソッドの時間計算量は O(n) であることに注意 const popFront: number = deque.shift() as number; const popBack: number = deque.pop() as number; -/* 両端キューの長さを取得 */ +/* 両端キューの長さを取得する */ const size: number = deque.length; -/* 両端キューが空かどうかを判定 */ +/* 両端キューが空かどうかを判定する */ const isEmpty: boolean = size === 0; ``` ```dart title="deque.dart" -/* 両端キューを初期化 */ -// Dart では Queue は両端キューとして定義されている -Queue deque = Queue(); +/* 両端キューを初期化する */ +// Dart では、Queue は両端キューとして定義されている +final Queue deque = Queue(); -/* 要素をエンキュー */ -deque.addLast(2); // 末尾に追加 +/* 要素をエンキューする */ +deque.addLast(2); // キューの末尾に追加する deque.addLast(5); deque.addLast(4); -deque.addFirst(3); // 先頭に追加 +deque.addFirst(3); // キューの先頭に追加する deque.addFirst(1); -/* 要素にアクセス */ -int peekFirst = deque.first; // 先頭要素 -int peekLast = deque.last; // 末尾要素 +/* 要素にアクセスする */ +final int peekFirst = deque.first; // キューの先頭要素 +final int peekLast = deque.last; // キューの末尾要素 -/* 要素をデキュー */ -int popFirst = deque.removeFirst(); // 先頭要素を取り出す -int popLast = deque.removeLast(); // 末尾要素を取り出す +/* 要素をデキューする */ +final int popFirst = deque.removeFirst(); // キューの先頭要素をデキューする +final int popLast = deque.removeLast(); // キューの末尾要素をデキューする -/* 両端キューの長さを取得 */ -int size = deque.length; +/* 両端キューの長さを取得する */ +final int size = deque.length; -/* 両端キューが空かどうかを判定 */ -bool isEmpty = deque.isEmpty; +/* 両端キューが空かどうかを判定する */ +final bool isEmpty = deque.isEmpty; ``` ```rust title="deque.rs" -/* 両端キューを初期化 */ -let mut deque: VecDeque = VecDeque::new(); +// 両端キューを初期化する +let mut deque: VecDeque = VecDeque::new(); -/* 要素をエンキュー */ -deque.push_back(2); // 末尾に追加 +/* 要素をエンキューする */ +deque.push_back(2); // キューの末尾に追加する deque.push_back(5); deque.push_back(4); -deque.push_front(3); // 先頭に追加 +deque.push_front(3); // キューの先頭に追加する deque.push_front(1); -/* 要素にアクセス */ -if let Some(front) = deque.front() { // 先頭要素 -} -if let Some(rear) = deque.back() { // 末尾要素 -} +// 要素にアクセスする +let peek_first = deque.front().unwrap(); // キューの先頭要素 +let peek_last = deque.back().unwrap(); // キューの末尾要素 -/* 要素をデキュー */ -if let Some(pop_front) = deque.pop_front() { // 先頭要素を取り出す -} -if let Some(pop_rear) = deque.pop_back() { // 末尾要素を取り出す -} +// 要素をデキューする +let pop_first = deque.pop_front().unwrap(); // キューの先頭要素をデキューする +let pop_last = deque.pop_back().unwrap(); // キューの末尾要素をデキューする -/* 両端キューの長さを取得 */ +// 両端キューの長さを取得する let size = deque.len(); -/* 両端キューが空かどうかを判定 */ +// 両端キューが空かどうかを判定する let is_empty = deque.is_empty(); ``` @@ -281,57 +277,57 @@ let is_empty = deque.is_empty(); ``` ```kotlin title="deque.kt" -/* 両端キューを初期化 */ +/* 両端キューを初期化する */ val deque = LinkedList() -/* 要素をエンキュー */ -deque.offerLast(2) // 末尾に追加 +/* 要素をエンキューする */ +deque.offerLast(2) // キューの末尾に追加する deque.offerLast(5) deque.offerLast(4) -deque.offerFirst(3) // 先頭に追加 +deque.offerFirst(3) // キューの先頭に追加する deque.offerFirst(1) -/* 要素にアクセス */ -val peekFirst = deque.peekFirst() // 先頭要素 -val peekLast = deque.peekLast() // 末尾要素 +/* 要素にアクセスする */ +val peekFirst = deque.peekFirst() // キューの先頭要素 +val peekLast = deque.peekLast() // キューの末尾要素 -/* 要素をデキュー */ -val popFirst = deque.pollFirst() // 先頭要素を取り出す -val popLast = deque.pollLast() // 末尾要素を取り出す +/* 要素をデキューする */ +val popFirst = deque.pollFirst() // キューの先頭要素をデキューする +val popLast = deque.pollLast() // キューの末尾要素をデキューする -/* 両端キューの長さを取得 */ +/* 両端キューの長さを取得する */ val size = deque.size -/* 両端キューが空かどうかを判定 */ +/* 両端キューが空かどうかを判定する */ val isEmpty = deque.isEmpty() ``` ```ruby title="deque.rb" -# 両端キューを初期化 -# Ruby には組み込みの両端キューがないため、Array で代用する必要がある +# 両端キューを初期化する +# Ruby には組み込みの両端キューがないため、Array を両端キューとして使うしかない deque = [] -# 要素をエンキュー +# 要素をエンキューする deque << 2 deque << 5 deque << 4 -# 配列なので Array#unshift の時間計算量は O(n) であることに注意 +# 配列なので Array#unshift メソッドの時間計算量は O(n) であることに注意 deque.unshift(3) deque.unshift(1) -# 要素にアクセス +# 要素にアクセスする peek_first = deque.first peek_last = deque.last -# 要素をデキュー -# 配列なので Array#shift の時間計算量は O(n) であることに注意 +# 要素をデキューする +# 配列なので Array#shift メソッドの時間計算量は O(n) であることに注意 pop_front = deque.shift pop_back = deque.pop -# 両端キューの長さを取得 +# 両端キューの長さを取得する size = deque.length -# 両端キューが空かどうかを判定 +# 両端キューが空かどうかを判定する is_empty = size.zero? ``` diff --git a/ja/codes/snippets/chapter_stack_and_queue/queue.md b/ja/codes/snippets/chapter_stack_and_queue/queue.md index 99eec9684..9cdb80260 100644 --- a/ja/codes/snippets/chapter_stack_and_queue/queue.md +++ b/ja/codes/snippets/chapter_stack_and_queue/queue.md @@ -2,257 +2,255 @@ ```python title="queue.py" from collections import deque -# キューを初期化 -# Python では通常、両端キュークラス deque をキューとして使う -# queue.Queue() は本来のキュークラスだが、使いにくいため推奨しない +# キューを初期化する +# Python では一般に、両端キューのクラス deque をキューとして使う +# queue.Queue() は専用のキュークラスだが、やや使いづらいため推奨しない que: deque[int] = deque() -# 要素をエンキュー +# 要素をエンキューする que.append(1) que.append(3) que.append(2) que.append(5) que.append(4) -# 先頭要素にアクセス +# キューの先頭要素にアクセス front: int = que[0] -# 要素をデキュー +# 要素をデキューする pop: int = que.popleft() # キューの長さを取得 size: int = len(que) -# キューが空かどうかを判定 +# キューが空か判定 is_empty: bool = len(que) == 0 ``` ```cpp title="queue.cpp" -/* キューを初期化 */ +/* キューを初期化する */ queue queue; -/* 要素をエンキュー */ +/* 要素をエンキューする */ queue.push(1); queue.push(3); queue.push(2); queue.push(5); queue.push(4); -/* 先頭要素にアクセス */ +/* キューの先頭要素にアクセス */ int front = queue.front(); -/* 要素をデキュー */ +/* 要素をデキューする */ queue.pop(); /* キューの長さを取得 */ int size = queue.size(); -/* キューが空かどうかを判定 */ +/* キューが空か判定 */ bool empty = queue.empty(); ``` ```java title="queue.java" -/* キューを初期化 */ +/* キューを初期化する */ Queue queue = new LinkedList<>(); -/* 要素をエンキュー */ +/* 要素をエンキューする */ queue.offer(1); queue.offer(3); queue.offer(2); queue.offer(5); queue.offer(4); -/* 先頭要素にアクセス */ +/* キューの先頭要素にアクセス */ int peek = queue.peek(); -/* 要素をデキュー */ +/* 要素をデキューする */ int pop = queue.poll(); /* キューの長さを取得 */ int size = queue.size(); -/* キューが空かどうかを判定 */ +/* キューが空か判定 */ boolean isEmpty = queue.isEmpty(); ``` ```csharp title="queue.cs" -/* キューを初期化 */ +/* キューを初期化する */ Queue queue = new(); -/* 要素をエンキュー */ +/* 要素をエンキューする */ queue.Enqueue(1); queue.Enqueue(3); queue.Enqueue(2); queue.Enqueue(5); queue.Enqueue(4); -/* 先頭要素にアクセス */ +/* キューの先頭要素にアクセス */ int peek = queue.Peek(); -/* 要素をデキュー */ +/* 要素をデキューする */ int pop = queue.Dequeue(); /* キューの長さを取得 */ int size = queue.Count; -/* キューが空かどうかを判定 */ +/* キューが空か判定 */ bool isEmpty = queue.Count == 0; ``` ```go title="queue_test.go" -/* キューを初期化 */ +/* キューを初期化する */ // Go では list をキューとして使う queue := list.New() -/* 要素をエンキュー */ +/* 要素をエンキューする */ queue.PushBack(1) queue.PushBack(3) queue.PushBack(2) queue.PushBack(5) queue.PushBack(4) -/* 先頭要素にアクセス */ +/* キューの先頭要素にアクセス */ peek := queue.Front() -/* 要素をデキュー */ +/* 要素をデキューする */ pop := queue.Front() queue.Remove(pop) /* キューの長さを取得 */ size := queue.Len() -/* キューが空かどうかを判定 */ +/* キューが空か判定 */ isEmpty := queue.Len() == 0 ``` ```swift title="queue.swift" -/* キューを初期化 */ +/* キューを初期化する */ // Swift には組み込みのキュークラスがないため、Array をキューとして使える var queue: [Int] = [] -/* 要素をエンキュー */ +/* 要素をエンキューする */ queue.append(1) queue.append(3) queue.append(2) queue.append(5) queue.append(4) -/* 先頭要素にアクセス */ +/* キューの先頭要素にアクセス */ let peek = queue.first! -/* 要素をデキュー */ -// 配列なので removeFirst の計算量は O(n) +/* 要素をデキューする */ +// Array で再現する場合、removeFirst の計算量は O(n) let pop = queue.removeFirst() /* キューの長さを取得 */ let size = queue.count -/* キューが空かどうかを判定 */ +/* キューが空か判定 */ let isEmpty = queue.isEmpty ``` ```javascript title="queue.js" -/* キューを初期化 */ +/* キューを初期化する */ // JavaScript には組み込みのキューがないため、Array をキューとして使える const queue = []; -/* 要素をエンキュー */ +/* 要素をエンキューする */ queue.push(1); queue.push(3); queue.push(2); queue.push(5); queue.push(4); -/* 先頭要素にアクセス */ +/* キューの先頭要素にアクセス */ const peek = queue[0]; -/* 要素をデキュー */ -// 内部が配列なので shift() の時間計算量は O(n) +/* 要素をデキューする */ +// 内部は配列なので、shift() メソッドの時間計算量は O(n) const pop = queue.shift(); /* キューの長さを取得 */ const size = queue.length; -/* キューが空かどうかを判定 */ -const empty = queue.length === 0; +/* キューが空か判定 */ +const isEmpty = queue.length === 0; ``` ```typescript title="queue.ts" -/* キューを初期化 */ +/* キューを初期化する */ // TypeScript には組み込みのキューがないため、Array をキューとして使える const queue: number[] = []; -/* 要素をエンキュー */ +/* 要素をエンキューする */ queue.push(1); queue.push(3); queue.push(2); queue.push(5); queue.push(4); -/* 先頭要素にアクセス */ +/* キューの先頭要素にアクセス */ const peek = queue[0]; -/* 要素をデキュー */ -// 内部が配列なので shift() の時間計算量は O(n) +/* 要素をデキューする */ +// 内部は配列なので、shift() メソッドの時間計算量は O(n) const pop = queue.shift(); /* キューの長さを取得 */ const size = queue.length; -/* キューが空かどうかを判定 */ -const empty = queue.length === 0; +/* キューが空か判定 */ +const isEmpty = queue.length === 0; ``` ```dart title="queue.dart" -/* キューを初期化 */ -// Dart の Queue は両端キューであり、通常のキューとしても使える -Queue queue = Queue(); +/* キューを初期化する */ +// Dart では一般に、両端キューのクラス Queue をキューとして使う +final Queue queue = Queue(); -/* 要素をエンキュー */ +/* 要素をエンキューする */ queue.add(1); queue.add(3); queue.add(2); queue.add(5); queue.add(4); -/* 先頭要素にアクセス */ -int peek = queue.first; +/* キューの先頭要素にアクセス */ +final int peek = queue.first; -/* 要素をデキュー */ -int pop = queue.removeFirst(); +/* 要素をデキューする */ +final int pop = queue.removeFirst(); /* キューの長さを取得 */ -int size = queue.length; +final int size = queue.length; -/* キューが空かどうかを判定 */ -bool isEmpty = queue.isEmpty; +/* キューが空か判定 */ +final bool isEmpty = queue.isEmpty; ``` ```rust title="queue.rs" -/* 両端キューを初期化 */ -// Rust では両端キューを通常のキューとして使う -let mut deque: VecDeque = VecDeque::new(); +// キューを初期化する +// Rust では一般に、両端キュー VecDeque をキューとして使う +let mut queue: VecDeque = VecDeque::new(); -/* 要素をエンキュー */ -deque.push_back(1); -deque.push_back(3); -deque.push_back(2); -deque.push_back(5); -deque.push_back(4); +// 要素をエンキューする +queue.push_back(1); +queue.push_back(3); +queue.push_back(2); +queue.push_back(5); +queue.push_back(4); -/* 先頭要素にアクセス */ -if let Some(front) = deque.front() { -} +// キューの先頭要素にアクセス +let peek = queue.front().unwrap(); -/* 要素をデキュー */ -if let Some(pop) = deque.pop_front() { -} +// 要素をデキューする +let pop = queue.pop_front().unwrap(); -/* キューの長さを取得 */ -let size = deque.len(); +// キューの長さを取得 +let size = queue.len(); -/* キューが空かどうかを判定 */ -let is_empty = deque.is_empty(); +// キューが空か判定 +let is_empty = queue.is_empty(); ``` ```c title="queue.c" @@ -260,52 +258,52 @@ let is_empty = deque.is_empty(); ``` ```kotlin title="queue.kt" -/* キューを初期化 */ +/* キューを初期化する */ val queue = LinkedList() -/* 要素をエンキュー */ +/* 要素をエンキューする */ queue.offer(1) queue.offer(3) queue.offer(2) queue.offer(5) queue.offer(4) -/* 先頭要素にアクセス */ +/* キューの先頭要素にアクセス */ val peek = queue.peek() -/* 要素をデキュー */ +/* 要素をデキューする */ val pop = queue.poll() /* キューの長さを取得 */ val size = queue.size -/* キューが空かどうかを判定 */ +/* キューが空か判定 */ val isEmpty = queue.isEmpty() ``` ```ruby title="queue.rb" -# キューを初期化 -# Ruby の組み込みキュー(Thread::Queue)には peek や走査のメソッドがないため、Array をキューとして使える +# キューを初期化する +# Ruby の組み込みキュー(Thread::Queue)には peek と走査のメソッドがないため、Array をキューとして使える queue = [] -# 要素をエンキュー +# 要素をエンキューする queue.push(1) queue.push(3) queue.push(2) queue.push(5) queue.push(4) -# キューの要素にアクセス +# キューの要素にアクセスする peek = queue.first -# 要素をデキュー -# 配列なので Array#shift の時間計算量は O(n) であることに注意 +# 要素をデキューする +# 配列なので Array#shift メソッドの時間計算量は O(n) であることに注意 pop = queue.shift # キューの長さを取得 size = queue.length -# キューが空かどうかを判定 +# キューが空か判定 is_empty = queue.empty? ``` diff --git a/ja/codes/snippets/chapter_stack_and_queue/stack.md b/ja/codes/snippets/chapter_stack_and_queue/stack.md index 55e0080cd..fe0e7d2a3 100644 --- a/ja/codes/snippets/chapter_stack_and_queue/stack.md +++ b/ja/codes/snippets/chapter_stack_and_queue/stack.md @@ -1,249 +1,249 @@ ```python title="stack.py" -# スタックを初期化 +# スタックを初期化する # Python には組み込みのスタッククラスがないため、list をスタックとして使える stack: list[int] = [] -# 要素をプッシュ +# 要素をプッシュする stack.append(1) stack.append(3) stack.append(2) stack.append(5) stack.append(4) -# スタックの先頭要素にアクセス +# スタックの先頭要素にアクセスする peek: int = stack[-1] -# 要素をポップ +# 要素をポップする pop: int = stack.pop() -# スタックの長さを取得 +# スタックの長さを取得する size: int = len(stack) -# 空かどうかを判定 +# 空かどうかを判定する is_empty: bool = len(stack) == 0 ``` ```cpp title="stack.cpp" -/* スタックを初期化 */ +/* スタックを初期化する */ stack stack; -/* 要素をプッシュ */ +/* 要素をプッシュする */ stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* スタックの先頭要素にアクセス */ +/* スタックの先頭要素にアクセスする */ int top = stack.top(); -/* 要素をポップ */ +/* 要素をポップする */ stack.pop(); // 戻り値なし -/* スタックの長さを取得 */ +/* スタックの長さを取得する */ int size = stack.size(); -/* 空かどうかを判定 */ +/* 空かどうかを判定する */ bool empty = stack.empty(); ``` ```java title="stack.java" -/* スタックを初期化 */ +/* スタックを初期化する */ Stack stack = new Stack<>(); -/* 要素をプッシュ */ +/* 要素をプッシュする */ stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* スタックの先頭要素にアクセス */ +/* スタックの先頭要素にアクセスする */ int peek = stack.peek(); -/* 要素をポップ */ +/* 要素をポップする */ int pop = stack.pop(); -/* スタックの長さを取得 */ +/* スタックの長さを取得する */ int size = stack.size(); -/* 空かどうかを判定 */ +/* 空かどうかを判定する */ boolean isEmpty = stack.isEmpty(); ``` ```csharp title="stack.cs" -/* スタックを初期化 */ +/* スタックを初期化する */ Stack stack = new(); -/* 要素をプッシュ */ +/* 要素をプッシュする */ stack.Push(1); stack.Push(3); stack.Push(2); stack.Push(5); stack.Push(4); -/* スタックの先頭要素にアクセス */ +/* スタックの先頭要素にアクセスする */ int peek = stack.Peek(); -/* 要素をポップ */ +/* 要素をポップする */ int pop = stack.Pop(); -/* スタックの長さを取得 */ +/* スタックの長さを取得する */ int size = stack.Count; -/* 空かどうかを判定 */ +/* 空かどうかを判定する */ bool isEmpty = stack.Count == 0; ``` ```go title="stack_test.go" -/* スタックを初期化 */ -// Go では Slice をスタックとして使うことを推奨 +/* スタックを初期化する */ +// Go では Slice をスタックとして使うことを推奨する var stack []int -/* 要素をプッシュ */ +/* 要素をプッシュする */ stack = append(stack, 1) stack = append(stack, 3) stack = append(stack, 2) stack = append(stack, 5) stack = append(stack, 4) -/* スタックの先頭要素にアクセス */ +/* スタックの先頭要素にアクセスする */ peek := stack[len(stack)-1] -/* 要素をポップ */ +/* 要素をポップする */ pop := stack[len(stack)-1] stack = stack[:len(stack)-1] -/* スタックの長さを取得 */ +/* スタックの長さを取得する */ size := len(stack) -/* 空かどうかを判定 */ +/* 空かどうかを判定する */ isEmpty := len(stack) == 0 ``` ```swift title="stack.swift" -/* スタックを初期化 */ +/* スタックを初期化する */ // Swift には組み込みのスタッククラスがないため、Array をスタックとして使える var stack: [Int] = [] -/* 要素をプッシュ */ +/* 要素をプッシュする */ stack.append(1) stack.append(3) stack.append(2) stack.append(5) stack.append(4) -/* スタックの先頭要素にアクセス */ +/* スタックの先頭要素にアクセスする */ let peek = stack.last! -/* 要素をポップ */ +/* 要素をポップする */ let pop = stack.removeLast() -/* スタックの長さを取得 */ +/* スタックの長さを取得する */ let size = stack.count -/* 空かどうかを判定 */ +/* 空かどうかを判定する */ let isEmpty = stack.isEmpty ``` ```javascript title="stack.js" -/* スタックを初期化 */ +/* スタックを初期化する */ // JavaScript には組み込みのスタッククラスがないため、Array をスタックとして使える const stack = []; -/* 要素をプッシュ */ +/* 要素をプッシュする */ stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* スタックの先頭要素にアクセス */ -const peek = stack[stack.length-1]; +/* スタックの先頭要素にアクセスする */ +const peek = stack[stack.length - 1]; -/* 要素をポップ */ +/* 要素をポップする */ const pop = stack.pop(); -/* スタックの長さを取得 */ +/* スタックの長さを取得する */ const size = stack.length; -/* 空かどうかを判定 */ -const is_empty = stack.length === 0; +/* 空かどうかを判定する */ +const isEmpty = stack.length === 0; ``` ```typescript title="stack.ts" -/* スタックを初期化 */ +/* スタックを初期化する */ // TypeScript には組み込みのスタッククラスがないため、Array をスタックとして使える const stack: number[] = []; -/* 要素をプッシュ */ +/* 要素をプッシュする */ stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* スタックの先頭要素にアクセス */ +/* スタックの先頭要素にアクセスする */ const peek = stack[stack.length - 1]; -/* 要素をポップ */ +/* 要素をポップする */ const pop = stack.pop(); -/* スタックの長さを取得 */ +/* スタックの長さを取得する */ const size = stack.length; -/* 空かどうかを判定 */ -const is_empty = stack.length === 0; +/* 空かどうかを判定する */ +const isEmpty = stack.length === 0; ``` ```dart title="stack.dart" -/* スタックを初期化 */ +/* スタックを初期化する */ // Dart には組み込みのスタッククラスがないため、List をスタックとして使える -List stack = []; +final List stack = []; -/* 要素をプッシュ */ +/* 要素をプッシュする */ stack.add(1); stack.add(3); stack.add(2); stack.add(5); stack.add(4); -/* スタックの先頭要素にアクセス */ -int peek = stack.last; +/* スタックの先頭要素にアクセスする */ +final int peek = stack.last; -/* 要素をポップ */ -int pop = stack.removeLast(); +/* 要素をポップする */ +final int pop = stack.removeLast(); -/* スタックの長さを取得 */ -int size = stack.length; +/* スタックの長さを取得する */ +final int size = stack.length; -/* 空かどうかを判定 */ -bool isEmpty = stack.isEmpty; +/* 空かどうかを判定する */ +final bool isEmpty = stack.isEmpty; ``` ```rust title="stack.rs" -/* スタックを初期化 */ -// Vec をスタックとして使う +// スタックを初期化する +// Rust では Vec をスタックとして使うことを推奨する let mut stack: Vec = Vec::new(); -/* 要素をプッシュ */ +// 要素をプッシュする stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* スタックの先頭要素にアクセス */ -let top = stack.last().unwrap(); +// スタックの先頭要素にアクセスする +let peek = stack.last().unwrap(); -/* 要素をポップ */ +// 要素をポップする let pop = stack.pop().unwrap(); -/* スタックの長さを取得 */ +// スタックの長さを取得する let size = stack.len(); -/* 空かどうかを判定 */ +// スタックが空かどうかを判定する let is_empty = stack.is_empty(); ``` @@ -252,51 +252,51 @@ let is_empty = stack.is_empty(); ``` ```kotlin title="stack.kt" -/* スタックを初期化 */ +/* スタックを初期化する */ val stack = Stack() -/* 要素をプッシュ */ +/* 要素をプッシュする */ stack.push(1) stack.push(3) stack.push(2) stack.push(5) stack.push(4) -/* スタックの先頭要素にアクセス */ +/* スタックの先頭要素にアクセスする */ val peek = stack.peek() -/* 要素をポップ */ +/* 要素をポップする */ val pop = stack.pop() -/* スタックの長さを取得 */ +/* スタックの長さを取得する */ val size = stack.size -/* 空かどうかを判定 */ +/* 空かどうかを判定する */ val isEmpty = stack.isEmpty() ``` ```ruby title="stack.rb" -# スタックを初期化 +# スタックを初期化する # Ruby には組み込みのスタッククラスがないため、Array をスタックとして使える stack = [] -# 要素をプッシュ +# 要素をプッシュする stack << 1 stack << 3 stack << 2 stack << 5 stack << 4 -# スタックの先頭要素にアクセス +# スタックの先頭要素にアクセスする peek = stack.last -# 要素をポップ +# 要素をポップする pop = stack.pop -# スタックの長さを取得 +# スタックの長さを取得する size = stack.length -# 空かどうかを判定 +# 空かどうかを判定する is_empty = stack.empty? ``` diff --git a/ja/codes/snippets/chapter_tree/binary_tree.md b/ja/codes/snippets/chapter_tree/binary_tree.md index ecf40ac45..e364db8af 100644 --- a/ja/codes/snippets/chapter_tree/binary_tree.md +++ b/ja/codes/snippets/chapter_tree/binary_tree.md @@ -133,7 +133,6 @@ impl TreeNode { /* 二分木のノード構造体 */ typedef struct TreeNode { int val; // ノードの値 - int height; // ノードの高さ struct TreeNode *left; // 左の子へのポインタ struct TreeNode *right; // 右の子へのポインタ } TreeNode; @@ -144,7 +143,6 @@ TreeNode *newTreeNode(int val) { node = (TreeNode *)malloc(sizeof(TreeNode)); node->val = val; - node->height = 0; node->left = NULL; node->right = NULL; return node; @@ -174,14 +172,14 @@ end ```python title="binary_tree.py" -# 二分木を初期化 -# ノードを初期化 +# 二分木を初期化する +# ノードを初期化する n1 = TreeNode(val=1) n2 = TreeNode(val=2) n3 = TreeNode(val=3) n4 = TreeNode(val=4) n5 = TreeNode(val=5) -# ノード間の参照(ポインタ)をつなぐ +# ノード間の参照(ポインタ)を設定する n1.left = n2 n1.right = n3 n2.left = n4 @@ -189,14 +187,14 @@ n2.right = n5 ``` ```cpp title="binary_tree.cpp" -/* 二分木を初期化 */ -// ノードを初期化 -TreeNode* n1 = new TreeNode(1); -TreeNode* n2 = new TreeNode(2); -TreeNode* n3 = new TreeNode(3); -TreeNode* n4 = new TreeNode(4); -TreeNode* n5 = new TreeNode(5); -// ノード間の参照(ポインタ)をつなぐ +/* 二分木を初期化する */ +// ノードを初期化する +TreeNode *n1 = new TreeNode(1); +TreeNode *n2 = new TreeNode(2); +TreeNode *n3 = new TreeNode(3); +TreeNode *n4 = new TreeNode(4); +TreeNode *n5 = new TreeNode(5); +// ノード間の参照(ポインタ)を設定する n1->left = n2; n1->right = n3; n2->left = n4; @@ -204,13 +202,14 @@ n2->right = n5; ``` ```java title="binary_tree.java" -// ノードを初期化 +/* 二分木を初期化する */ +// ノードを初期化する TreeNode n1 = new TreeNode(1); TreeNode n2 = new TreeNode(2); TreeNode n3 = new TreeNode(3); TreeNode n4 = new TreeNode(4); TreeNode n5 = new TreeNode(5); -// ノード間の参照(ポインタ)をつなぐ +// ノード間の参照(ポインタ)を設定する n1.left = n2; n1.right = n3; n2.left = n4; @@ -218,14 +217,14 @@ n2.right = n5; ``` ```csharp title="binary_tree.cs" -/* 二分木を初期化 */ -// ノードを初期化 +/* 二分木を初期化する */ +// ノードを初期化する TreeNode n1 = new(1); TreeNode n2 = new(2); TreeNode n3 = new(3); TreeNode n4 = new(4); TreeNode n5 = new(5); -// ノード間の参照(ポインタ)をつなぐ +// ノード間の参照(ポインタ)を設定する n1.left = n2; n1.right = n3; n2.left = n4; @@ -233,14 +232,14 @@ n2.right = n5; ``` ```go title="binary_tree.go" -/* 二分木を初期化 */ -// ノードを初期化 +/* 二分木を初期化する */ +// ノードを初期化する n1 := NewTreeNode(1) n2 := NewTreeNode(2) n3 := NewTreeNode(3) n4 := NewTreeNode(4) n5 := NewTreeNode(5) -// ノード間の参照(ポインタ)をつなぐ +// ノード間の参照(ポインタ)を設定する n1.Left = n2 n1.Right = n3 n2.Left = n4 @@ -248,13 +247,14 @@ n2.Right = n5 ``` ```swift title="binary_tree.swift" -// ノードを初期化 +/* 二分木を初期化する */ +// ノードを初期化する let n1 = TreeNode(x: 1) let n2 = TreeNode(x: 2) let n3 = TreeNode(x: 3) let n4 = TreeNode(x: 4) let n5 = TreeNode(x: 5) -// ノード間の参照(ポインタ)をつなぐ +// ノード間の参照(ポインタ)を設定する n1.left = n2 n1.right = n3 n2.left = n4 @@ -262,14 +262,14 @@ n2.right = n5 ``` ```javascript title="binary_tree.js" -/* 二分木を初期化 */ -// ノードを初期化 +/* 二分木を初期化する */ +// ノードを初期化する let n1 = new TreeNode(1), n2 = new TreeNode(2), n3 = new TreeNode(3), n4 = new TreeNode(4), n5 = new TreeNode(5); -// ノード間の参照(ポインタ)をつなぐ +// ノード間の参照(ポインタ)を設定する n1.left = n2; n1.right = n3; n2.left = n4; @@ -277,14 +277,14 @@ n2.right = n5; ``` ```typescript title="binary_tree.ts" -/* 二分木を初期化 */ -// ノードを初期化 +/* 二分木を初期化する */ +// ノードを初期化する let n1 = new TreeNode(1), n2 = new TreeNode(2), n3 = new TreeNode(3), n4 = new TreeNode(4), n5 = new TreeNode(5); -// ノード間の参照(ポインタ)をつなぐ +// ノード間の参照(ポインタ)を設定する n1.left = n2; n1.right = n3; n2.left = n4; @@ -292,14 +292,14 @@ n2.right = n5; ``` ```dart title="binary_tree.dart" -/* 二分木を初期化 */ -// ノードを初期化 -TreeNode n1 = new TreeNode(1); -TreeNode n2 = new TreeNode(2); -TreeNode n3 = new TreeNode(3); -TreeNode n4 = new TreeNode(4); -TreeNode n5 = new TreeNode(5); -// ノード間の参照(ポインタ)をつなぐ +/* 二分木を初期化する */ +// ノードを初期化する +TreeNode n1 = TreeNode(1); +TreeNode n2 = TreeNode(2); +TreeNode n3 = TreeNode(3); +TreeNode n4 = TreeNode(4); +TreeNode n5 = TreeNode(5); +// ノード間の参照(ポインタ)を設定する n1.left = n2; n1.right = n3; n2.left = n4; @@ -307,28 +307,29 @@ n2.right = n5; ``` ```rust title="binary_tree.rs" -// ノードを初期化 +/* 二分木を初期化する */ +// ノードを初期化する let n1 = TreeNode::new(1); let n2 = TreeNode::new(2); let n3 = TreeNode::new(3); let n4 = TreeNode::new(4); let n5 = TreeNode::new(5); -// ノード間の参照(ポインタ)をつなぐ -n1.borrow_mut().left = Some(n2.clone()); -n1.borrow_mut().right = Some(n3); -n2.borrow_mut().left = Some(n4); -n2.borrow_mut().right = Some(n5); +// ノード間の参照(ポインタ)を設定する +n1.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().right = Some(Rc::clone(&n3)); +n2.borrow_mut().left = Some(Rc::clone(&n4)); +n2.borrow_mut().right = Some(Rc::clone(&n5)); ``` ```c title="binary_tree.c" -/* 二分木を初期化 */ -// ノードを初期化 +/* 二分木を初期化する */ +// ノードを初期化する TreeNode *n1 = newTreeNode(1); TreeNode *n2 = newTreeNode(2); TreeNode *n3 = newTreeNode(3); TreeNode *n4 = newTreeNode(4); TreeNode *n5 = newTreeNode(5); -// ノード間の参照(ポインタ)をつなぐ +// ノード間の参照(ポインタ)を設定する n1->left = n2; n1->right = n3; n2->left = n4; @@ -336,13 +337,14 @@ n2->right = n5; ``` ```kotlin title="binary_tree.kt" -// ノードを初期化 +/* 二分木を初期化する */ +// ノードを初期化する val n1 = TreeNode(1) val n2 = TreeNode(2) val n3 = TreeNode(3) val n4 = TreeNode(4) val n5 = TreeNode(5) -// ノード間の参照(ポインタ)をつなぐ +// ノード間の参照(ポインタ)を設定する n1.left = n2 n1.right = n3 n2.left = n4 @@ -350,14 +352,14 @@ n2.right = n5 ``` ```ruby title="binary_tree.rb" -# 二分木を初期化 -# ノードを初期化 +# 二分木を初期化する +# ノードを初期化する n1 = TreeNode.new(1) n2 = TreeNode.new(2) n3 = TreeNode.new(3) n4 = TreeNode.new(4) n5 = TreeNode.new(5) -# ノード間の参照(ポインタ)をつなぐ +# ノード間の参照(ポインタ)を設定する n1.left = n2 n1.right = n3 n2.left = n4 @@ -370,133 +372,137 @@ https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%2 ```python title="binary_tree.py" # ノードの挿入と削除 -p = TreeNode(0) -# n1 -> n2 の間にノード P を挿入 -n1.left = p -p.left = n2 -# ノード P を削除 +P = TreeNode(0) +# n1 -> n2 の間にノード P を挿入する +n1.left = P +P.left = n2 +# ノード P を削除する n1.left = n2 ``` ```cpp title="binary_tree.cpp" /* ノードの挿入と削除 */ -TreeNode* P = new TreeNode(0); -// n1 -> n2 の間にノード P を挿入 +TreeNode *P = new TreeNode(0); +// n1 -> n2 の間にノード P を挿入する n1->left = P; P->left = n2; -// ノード P を削除 +// ノード P を削除する n1->left = n2; -// メモリを解放 -delete P; +delete P; // メモリを解放する ``` ```java title="binary_tree.java" +/* ノードの挿入と削除 */ TreeNode P = new TreeNode(0); -// n1 -> n2 の間にノード P を挿入 +// n1 -> n2 の間にノード P を挿入する n1.left = P; P.left = n2; -// ノード P を削除 +// ノード P を削除する n1.left = n2; ``` ```csharp title="binary_tree.cs" /* ノードの挿入と削除 */ TreeNode P = new(0); -// n1 -> n2 の間にノード P を挿入 +// n1 -> n2 の間にノード P を挿入する n1.left = P; P.left = n2; -// ノード P を削除 +// ノード P を削除する n1.left = n2; ``` ```go title="binary_tree.go" /* ノードの挿入と削除 */ -// n1 -> n2 の間にノード P を挿入 +// n1 -> n2 の間にノード P を挿入する p := NewTreeNode(0) n1.Left = p p.Left = n2 -// ノード P を削除 +// ノード P を削除する n1.Left = n2 ``` ```swift title="binary_tree.swift" +/* ノードの挿入と削除 */ let P = TreeNode(x: 0) -// n1 -> n2 の間にノード P を挿入 +// n1 -> n2 の間にノード P を挿入する n1.left = P P.left = n2 -// ノード P を削除 +// ノード P を削除する n1.left = n2 ``` ```javascript title="binary_tree.js" /* ノードの挿入と削除 */ -let P = new TreeNode(0); -// n1 -> n2 の間にノード P を挿入 +const P = new TreeNode(0); +// n1 -> n2 の間にノード P を挿入する n1.left = P; P.left = n2; -// ノード P を削除 +// ノード P を削除する n1.left = n2; ``` ```typescript title="binary_tree.ts" /* ノードの挿入と削除 */ const P = new TreeNode(0); -// n1 -> n2 の間にノード P を挿入 +// n1 -> n2 の間にノード P を挿入する n1.left = P; P.left = n2; -// ノード P を削除 +// ノード P を削除する n1.left = n2; ``` ```dart title="binary_tree.dart" /* ノードの挿入と削除 */ -TreeNode P = new TreeNode(0); -// n1 -> n2 の間にノード P を挿入 -n1.left = P; -P.left = n2; -// ノード P を削除 +TreeNode p = TreeNode(0); +// n1 -> n2 の間にノード P を挿入する +n1.left = p; +p.left = n2; +// ノード P を削除する n1.left = n2; ``` ```rust title="binary_tree.rs" +/* ノードの挿入と削除 */ let p = TreeNode::new(0); -// n1 -> n2 の間にノード P を挿入 -n1.borrow_mut().left = Some(p.clone()); -p.borrow_mut().left = Some(n2.clone()); -// ノード p を削除 -n1.borrow_mut().left = Some(n2); +// n1 -> n2 の間にノード P を挿入する +p.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().left = Some(Rc::clone(&p)); +// ノード P を削除する +drop(p); +n1.borrow_mut().left = Some(Rc::clone(&n2)); ``` ```c title="binary_tree.c" /* ノードの挿入と削除 */ TreeNode *P = newTreeNode(0); -// n1 -> n2 の間にノード P を挿入 +// n1 -> n2 の間にノード P を挿入する n1->left = P; P->left = n2; -// ノード P を削除 +// ノード P を削除する n1->left = n2; -// メモリを解放 +// メモリを解放する free(P); ``` ```kotlin title="binary_tree.kt" +/* ノードの挿入と削除 */ val P = TreeNode(0) -// n1 -> n2 の間にノード P を挿入 +// n1 -> n2 の間にノード P を挿入する n1.left = P P.left = n2 -// ノード P を削除 +// ノード P を削除する n1.left = n2 ``` ```ruby title="binary_tree.rb" # ノードの挿入と削除 _p = TreeNode.new(0) -# n1 -> n2 の間にノード _p を挿入 +# n1 -> n2 の間にノード _p を挿入する n1.left = _p _p.left = n2 -# ノードを削除 +# ノードを削除する n1.left = n2 ``` -https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9C%A8%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9C%A8%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20n1%20%3D%20TreeNode(val%3D1)%0A%20%20%20%20n2%20%3D%20TreeNode(val%3D2)%0A%20%20%20%20n3%20%3D%20TreeNode(val%3D3)%0A%20%20%20%20n4%20%3D%20TreeNode(val%3D4)%0A%20%20%20%20n5%20%3D%20TreeNode(val%3D5)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E9%96%93%E3%81%AE%E5%8F%82%E7%85%A7%EF%BC%88%E3%83%9D%E3%82%A4%E3%83%B3%E3%82%BF%EF%BC%89%E3%82%92%E3%81%A4%E3%81%AA%E3%81%90%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E6%8C%BF%E5%85%A5%E3%81%A8%E5%89%8A%E9%99%A4%0A%20%20%20%20p%20%3D%20TreeNode(0)%0A%20%20%20%20%23%20n1%20-%3E%20n2%20%E3%81%AE%E9%96%93%E3%81%AB%E3%83%8E%E3%83%BC%E3%83%89%20P%20%E3%82%92%E6%8C%BF%E5%85%A5%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%20P%20%E3%82%92%E5%89%8A%E9%99%A4%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%88%86%E6%9C%A8%E3%81%AE%E3%83%8E%E3%83%BC%E3%83%89%E3%82%AF%E3%83%A9%E3%82%B9%22%22%22%0A%20%20%20%20def%20__init__(self%2C%20val%3A%20int)%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E5%80%A4%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E3%81%AE%E5%AD%90%E3%81%B8%E3%81%AE%E5%8F%82%E7%85%A7%0A%0A%22%22%22%E5%AE%9F%E8%A1%8C%E7%94%A8%E3%82%B3%E3%83%BC%E3%83%89%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E4%BA%8C%E5%88%86%E6%9C%A8%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%82%92%E5%88%9D%E6%9C%9F%E5%8C%96%0A%20%20%20%20n1%20%3D%20TreeNode(val%3D1)%0A%20%20%20%20n2%20%3D%20TreeNode(val%3D2)%0A%20%20%20%20n3%20%3D%20TreeNode(val%3D3)%0A%20%20%20%20n4%20%3D%20TreeNode(val%3D4)%0A%20%20%20%20n5%20%3D%20TreeNode(val%3D5)%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E9%96%93%E3%81%AE%E5%8F%82%E7%85%A7%EF%BC%88%E3%83%9D%E3%82%A4%E3%83%B3%E3%82%BF%EF%BC%89%E3%82%92%E3%81%A4%E3%81%AA%E3%81%90%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%E3%81%AE%E6%8C%BF%E5%85%A5%E3%81%A8%E5%89%8A%E9%99%A4%0A%20%20%20%20P%20%3D%20TreeNode(0)%0A%20%20%20%20%23%20n1%20-%3E%20n2%20%E3%81%AE%E9%96%93%E3%81%AB%E3%83%8E%E3%83%BC%E3%83%89%20P%20%E3%82%92%E6%8C%BF%E5%85%A5%0A%20%20%20%20n1.left%20%3D%20P%0A%20%20%20%20P.left%20%3D%20n2%0A%20%20%20%20%23%20%E3%83%8E%E3%83%BC%E3%83%89%20P%20%E3%82%92%E5%89%8A%E9%99%A4%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ja/codes/swift/chapter_stack_and_queue/deque.swift b/ja/codes/swift/chapter_stack_and_queue/deque.swift index e374623f1..26ee07c19 100644 --- a/ja/codes/swift/chapter_stack_and_queue/deque.swift +++ b/ja/codes/swift/chapter_stack_and_queue/deque.swift @@ -27,7 +27,7 @@ enum Deque { print("キューの末尾要素 peekLast = \(peekLast)") /* 要素をデキューする */ - // Array で再現する場合、popFirst の計算量は O(n) + // Array で再現する場合、removeFirst の計算量は O(n) let popFirst = deque.removeFirst() print("先頭からデキューした要素 popFirst = \(popFirst)、先頭からデキューした後 deque = \(deque)") let popLast = deque.removeLast() diff --git a/ja/codes/swift/chapter_stack_and_queue/queue.swift b/ja/codes/swift/chapter_stack_and_queue/queue.swift index 58d96ff79..66ba91bff 100644 --- a/ja/codes/swift/chapter_stack_and_queue/queue.swift +++ b/ja/codes/swift/chapter_stack_and_queue/queue.swift @@ -25,7 +25,7 @@ enum Queue { print("キューの先頭要素 peek = \(peek)") /* 要素をデキューする */ - // Array で再現する場合、pop の計算量は O(n) + // Array で再現する場合、removeFirst の計算量は O(n) let pop = queue.removeFirst() print("デキューした要素 pop = \(pop)、デキュー後 queue = \(queue)") diff --git a/ja/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts b/ja/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts index 7a4140bd3..5fcd3d811 100644 --- a/ja/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/ja/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -6,8 +6,8 @@ /* 双方向連結リストのノード */ class ListNode { - prev: ListNode; // 前のノードへの参照(ポインタ) - next: ListNode; // 後続ノードへの参照(ポインタ) + prev: ListNode | null; // 前のノードへの参照(ポインタ) + next: ListNode | null; // 後続ノードへの参照(ポインタ) val: number; // ノードの値 constructor(val: number) { diff --git a/ko/codes/c/chapter_array_and_linkedlist/array.c b/ko/codes/c/chapter_array_and_linkedlist/array.c index 3b7a20145..863abccaa 100644 --- a/ko/codes/c/chapter_array_and_linkedlist/array.c +++ b/ko/codes/c/chapter_array_and_linkedlist/array.c @@ -75,7 +75,7 @@ int main() { /* 배열 초기화 */ int size = 5; - int arr[5]; + int arr[5] = {0}; printf("배열 arr = "); printArray(arr, size); diff --git a/ko/codes/c/chapter_graph/graph_bfs.c b/ko/codes/c/chapter_graph/graph_bfs.c index 7a0687410..972ed8fd7 100644 --- a/ko/codes/c/chapter_graph/graph_bfs.c +++ b/ko/codes/c/chapter_graph/graph_bfs.c @@ -27,14 +27,14 @@ int isEmpty(Queue *q) { return q->size == 0; } -/* 큐 삽입 연산 */ +/* 원소 삽입 연산 */ void enqueue(Queue *q, Vertex *vet) { q->vertices[q->rear] = vet; q->rear = (q->rear + 1) % MAX_SIZE; q->size++; } -/* 큐에서 꺼내는 연산 */ +/* 원소를 꺼내는 연산 */ Vertex *dequeue(Queue *q) { Vertex *vet = q->vertices[q->front]; q->front = (q->front + 1) % MAX_SIZE; diff --git a/ko/codes/c/chapter_stack_and_queue/array_deque.c b/ko/codes/c/chapter_stack_and_queue/array_deque.c index 13f00553f..340fa55d3 100644 --- a/ko/codes/c/chapter_stack_and_queue/array_deque.c +++ b/ko/codes/c/chapter_stack_and_queue/array_deque.c @@ -141,7 +141,7 @@ int main() { int peekLastNum = peekLast(deque); printf("맨 뒤 원소 peekLast = %d\r\n", peekLastNum); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ pushLast(deque, 4); printf("원소 4를 맨 뒤에 삽입한 후 deque = "); printArray(toArray(deque, &queSize), queSize); @@ -149,7 +149,7 @@ int main() { printf("원소 1을 맨 앞에 삽입한 후 deque = "); printArray(toArray(deque, &queSize), queSize); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int popLastNum = popLast(deque); printf("맨 뒤에서 꺼낸 원소 = %d, 꺼낸 후 deque= ", popLastNum); printArray(toArray(deque, &queSize), queSize); diff --git a/ko/codes/c/chapter_stack_and_queue/array_queue.c b/ko/codes/c/chapter_stack_and_queue/array_queue.c index 168360099..9de460b4b 100644 --- a/ko/codes/c/chapter_stack_and_queue/array_queue.c +++ b/ko/codes/c/chapter_stack_and_queue/array_queue.c @@ -51,7 +51,7 @@ int peek(ArrayQueue *queue) { return queue->nums[queue->front]; } -/* 큐에 삽입 */ +/* 원소 삽입 */ void push(ArrayQueue *queue, int num) { if (size(queue) == capacity(queue)) { printf("큐가 가득 찼다\r\n"); @@ -65,7 +65,7 @@ void push(ArrayQueue *queue, int num) { queue->queSize++; } -/* 큐에서 꺼내기 */ +/* 원소 꺼내기 */ int pop(ArrayQueue *queue) { int num = peek(queue); // 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -93,7 +93,7 @@ int main() { int queSize; ArrayQueue *queue = newArrayQueue(capacity); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ push(queue, 1); push(queue, 3); push(queue, 2); @@ -106,7 +106,7 @@ int main() { int peekNum = peek(queue); printf("큐의 맨 앞 원소 peek = %d\r\n", peekNum); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ peekNum = pop(queue); printf("큐에서 꺼낸 원소 pop = %d, 꺼낸 후 queue = ", peekNum); printArray(toArray(queue, &queSize), queSize); @@ -123,7 +123,7 @@ int main() { for (int i = 0; i < 10; i++) { push(queue, i); pop(queue); - printf("%d번째 삽입 + 꺼내기 후 queue = ", i); + printf("반복 %d 회차에서 삽입 + 꺼내기를 수행한 후 queue = ", i); printArray(toArray(queue, &queSize), queSize); } diff --git a/ko/codes/c/chapter_stack_and_queue/linkedlist_deque.c b/ko/codes/c/chapter_stack_and_queue/linkedlist_deque.c index a119c6ff3..0c18d5eb8 100644 --- a/ko/codes/c/chapter_stack_and_queue/linkedlist_deque.c +++ b/ko/codes/c/chapter_stack_and_queue/linkedlist_deque.c @@ -64,7 +64,7 @@ bool empty(LinkedListDeque *deque) { return (size(deque) == 0); } -/* 큐에 삽입 */ +/* 원소 삽입 */ void push(LinkedListDeque *deque, int num, bool isFront) { DoublyListNode *node = newDoublyListNode(num); // 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다 @@ -110,7 +110,7 @@ int peekLast(LinkedListDeque *deque) { return deque->rear->val; } -/* 큐에서 꺼내기 */ +/* 원소 꺼내기 */ int pop(LinkedListDeque *deque, bool isFront) { if (empty(deque)) return -1; @@ -182,9 +182,9 @@ int main() { int peekFirstNum = peekFirst(deque); printf("맨 앞 원소 peekFirst = %d\r\n", peekFirstNum); int peekLastNum = peekLast(deque); - printf("맨 앞 원소 peekLast = %d\r\n", peekLastNum); + printf("맨 뒤 원소 peekLast = %d\r\n", peekLastNum); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ pushLast(deque, 4); printf("원소 4를 맨 뒤에 삽입한 후 deque ="); printLinkedListDeque(deque); @@ -192,7 +192,7 @@ int main() { printf("원소 1을 맨 앞에 삽입한 후 deque ="); printLinkedListDeque(deque); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int popLastNum = popLast(deque); printf("맨 뒤에서 꺼낸 원소 popLast = %d, 꺼낸 후 deque = ", popLastNum); printLinkedListDeque(deque); diff --git a/ko/codes/c/chapter_stack_and_queue/linkedlist_queue.c b/ko/codes/c/chapter_stack_and_queue/linkedlist_queue.c index 321ce5112..004700573 100644 --- a/ko/codes/c/chapter_stack_and_queue/linkedlist_queue.c +++ b/ko/codes/c/chapter_stack_and_queue/linkedlist_queue.c @@ -43,7 +43,7 @@ bool empty(LinkedListQueue *queue) { return (size(queue) == 0); } -/* 큐에 삽입 */ +/* 원소 삽입 */ void push(LinkedListQueue *queue, int num) { // 꼬리 노드 위치에 node를 추가한다 ListNode *node = newListNode(num); @@ -66,7 +66,7 @@ int peek(LinkedListQueue *queue) { return queue->front->val; } -/* 큐에서 꺼내기 */ +/* 원소 꺼내기 */ int pop(LinkedListQueue *queue) { int num = peek(queue); ListNode *tmp = queue->front; @@ -95,7 +95,7 @@ int main() { /* 큐 초기화 */ LinkedListQueue *queue = newLinkedListQueue(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ push(queue, 1); push(queue, 3); push(queue, 2); @@ -108,7 +108,7 @@ int main() { int peekNum = peek(queue); printf("큐의 맨 앞 원소 peek = %d\r\n", peekNum); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ peekNum = pop(queue); printf("큐에서 꺼낸 원소 pop = %d, 꺼낸 후 queue = ", peekNum); printLinkedListQueue(queue); diff --git a/ko/codes/c/utils/list_node.h b/ko/codes/c/utils/list_node.h index 23203a5fb..5c32696e9 100644 --- a/ko/codes/c/utils/list_node.h +++ b/ko/codes/c/utils/list_node.h @@ -14,7 +14,7 @@ extern "C" { /* 연결 리스트 노드 구조체 */ typedef struct ListNode { int val; // 노드 값 - struct ListNode *next; // 다음 노드를 가리키는 참조 + struct ListNode *next; // 다음 노드를 가리키는 포인터 } ListNode; /* 생성자: 새 노드를 초기화한다 */ diff --git a/ko/codes/cpp/chapter_array_and_linkedlist/array.cpp b/ko/codes/cpp/chapter_array_and_linkedlist/array.cpp index e910ed2b1..cc4c01714 100644 --- a/ko/codes/cpp/chapter_array_and_linkedlist/array.cpp +++ b/ko/codes/cpp/chapter_array_and_linkedlist/array.cpp @@ -18,7 +18,7 @@ int randomAccess(int *nums, int size) { /* 배열 길이 확장 */ int *extend(int *nums, int size, int enlarge) { // 길이를 확장한 배열을 초기화한다 - int *res = new int[size + enlarge]; + int *res = new int[size + enlarge]{}; // 원래 배열의 모든 원소를 새 배열에 복사한다 for (int i = 0; i < size; i++) { res[i] = nums[i]; @@ -69,7 +69,7 @@ int find(int *nums, int size, int target) { int main() { /* 배열 초기화 */ int size = 5; - int *arr = new int[size]; + int *arr = new int[size]{}; cout << "배열 arr = "; printArray(arr, size); diff --git a/ko/codes/cpp/chapter_hashing/built_in_hash.cpp b/ko/codes/cpp/chapter_hashing/built_in_hash.cpp index d5cebce2b..4bb423f0c 100644 --- a/ko/codes/cpp/chapter_hashing/built_in_hash.cpp +++ b/ko/codes/cpp/chapter_hashing/built_in_hash.cpp @@ -10,19 +10,19 @@ int main() { int num = 3; size_t hashNum = hash()(num); - cout << "정수 " << num << " ; 해시값: " << hashNum << "\n"; + cout << "정수 " << num << " → 해시값: " << hashNum << "\n"; bool bol = true; size_t hashBol = hash()(bol); - cout << "불리언 값 " << bol << " ; 해시값: " << hashBol << "\n"; + cout << "불리언 값 " << bol << " → 해시값: " << hashBol << "\n"; double dec = 3.14159; size_t hashDec = hash()(dec); - cout << "소수 " << dec << " ; 해시값: " << hashDec << "\n"; + cout << "소수 " << dec << " → 해시값: " << hashDec << "\n"; string str = "Hello 算法"; size_t hashStr = hash()(str); - cout << "문자열 " << str << " ; 해시값: " << hashStr << "\n"; + cout << "문자열 " << str << " → 해시값: " << hashStr << "\n"; // C++의 내장 std::hash()는 기본 데이터 타입에 대한 해시값 계산만 제공한다 // 배열과 객체의 해시값 계산은 직접 구현해야 한다 diff --git a/ko/codes/cpp/chapter_stack_and_queue/array_deque.cpp b/ko/codes/cpp/chapter_stack_and_queue/array_deque.cpp index 43730b7b3..95dc0f841 100644 --- a/ko/codes/cpp/chapter_stack_and_queue/array_deque.cpp +++ b/ko/codes/cpp/chapter_stack_and_queue/array_deque.cpp @@ -129,7 +129,7 @@ int main() { int peekLast = deque->peekLast(); cout << "맨 뒤 원소 peekLast = " << peekLast << endl; - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque->pushLast(4); cout << "원소 4를 맨 뒤에 삽입한 후 deque = "; printVector(deque->toVector()); @@ -137,7 +137,7 @@ int main() { cout << "원소 1을 맨 앞에 삽입한 후 deque = "; printVector(deque->toVector()); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int popLast = deque->popLast(); cout << "맨 뒤에서 꺼낸 원소 = " << popLast << ", 맨 뒤에서 꺼낸 후 deque = "; printVector(deque->toVector()); diff --git a/ko/codes/cpp/chapter_stack_and_queue/array_queue.cpp b/ko/codes/cpp/chapter_stack_and_queue/array_queue.cpp index f781beace..c8e99edad 100644 --- a/ko/codes/cpp/chapter_stack_and_queue/array_queue.cpp +++ b/ko/codes/cpp/chapter_stack_and_queue/array_queue.cpp @@ -41,7 +41,7 @@ class ArrayQueue { return size() == 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ void push(int num) { if (queSize == queCapacity) { cout << "큐가 가득 찼다" << endl; @@ -55,7 +55,7 @@ class ArrayQueue { queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ int pop() { int num = peek(); // 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -88,7 +88,7 @@ int main() { int capacity = 10; ArrayQueue *queue = new ArrayQueue(capacity); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue->push(1); queue->push(3); queue->push(2); @@ -101,7 +101,7 @@ int main() { int peek = queue->peek(); cout << "맨 앞 원소 peek = " << peek << endl; - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ peek = queue->pop(); cout << "큐에서 꺼낸 원소 pop = " << peek << ", 큐에서 꺼낸 후 queue = "; printVector(queue->toVector()); @@ -118,7 +118,7 @@ int main() { for (int i = 0; i < 10; i++) { queue->push(i); queue->pop(); - cout << "반복 " << i << " 회에서 삽입 + 꺼내기를 수행한 후 queue = "; + cout << "반복 " << i << " 회차에서 삽입 + 꺼내기를 수행한 후 queue = "; printVector(queue->toVector()); } diff --git a/ko/codes/cpp/chapter_stack_and_queue/deque.cpp b/ko/codes/cpp/chapter_stack_and_queue/deque.cpp index 9cfed5c17..a7bcc9d89 100644 --- a/ko/codes/cpp/chapter_stack_and_queue/deque.cpp +++ b/ko/codes/cpp/chapter_stack_and_queue/deque.cpp @@ -11,7 +11,7 @@ int main() { /* 덱 초기화 */ deque deque; - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.push_back(2); deque.push_back(5); deque.push_back(4); @@ -26,7 +26,7 @@ int main() { int back = deque.back(); cout << "큐의 맨 뒤 원소 back = " << back << endl; - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ deque.pop_front(); cout << "맨 앞에서 꺼낸 원소 popFront = " << front << ", 맨 앞에서 꺼낸 후 deque = "; printDeque(deque); diff --git a/ko/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp b/ko/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp index 07ce63df8..ce6287503 100644 --- a/ko/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp +++ b/ko/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp @@ -47,7 +47,7 @@ class LinkedListDeque { return size() == 0; } - /* 큐 삽입 연산 */ + /* 원소 삽입 연산 */ void push(int num, bool isFront) { DoublyListNode *node = new DoublyListNode(num); // 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다 @@ -79,7 +79,7 @@ class LinkedListDeque { push(num, false); } - /* 큐에서 꺼내는 연산 */ + /* 원소를 꺼내는 연산 */ int pop(bool isFront) { if (isEmpty()) throw out_of_range("큐가 비어 있다"); @@ -166,7 +166,7 @@ int main() { int peekLast = deque->peekLast(); cout << "맨 뒤 원소 peekLast = " << peekLast << endl; - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque->pushLast(4); cout << "원소 4를 맨 뒤에 삽입한 후 deque ="; printVector(deque->toVector()); @@ -174,7 +174,7 @@ int main() { cout << "원소 1을 맨 앞에 삽입한 후 deque = "; printVector(deque->toVector()); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int popLast = deque->popLast(); cout << "맨 뒤에서 꺼낸 원소 = " << popLast << ", 맨 뒤에서 꺼낸 후 deque = "; printVector(deque->toVector()); diff --git a/ko/codes/cpp/chapter_stack_and_queue/linkedlist_queue.cpp b/ko/codes/cpp/chapter_stack_and_queue/linkedlist_queue.cpp index 3a2efa2b8..03e30c60f 100644 --- a/ko/codes/cpp/chapter_stack_and_queue/linkedlist_queue.cpp +++ b/ko/codes/cpp/chapter_stack_and_queue/linkedlist_queue.cpp @@ -34,7 +34,7 @@ class LinkedListQueue { return queSize == 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ void push(int num) { // 꼬리 노드 뒤에 num을 추가한다 ListNode *node = new ListNode(num); @@ -51,7 +51,7 @@ class LinkedListQueue { queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ int pop() { int num = peek(); // 머리 노드를 삭제한다 @@ -87,7 +87,7 @@ int main() { /* 큐 초기화 */ LinkedListQueue *queue = new LinkedListQueue(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue->push(1); queue->push(3); queue->push(2); @@ -100,7 +100,7 @@ int main() { int peek = queue->peek(); cout << "맨 앞 원소 peek = " << peek << endl; - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ peek = queue->pop(); cout << "큐에서 꺼낸 원소 pop = " << peek << ", 큐에서 꺼낸 후 queue = "; printVector(queue->toVector()); diff --git a/ko/codes/cpp/chapter_stack_and_queue/queue.cpp b/ko/codes/cpp/chapter_stack_and_queue/queue.cpp index 08caeaa0f..626ab00c8 100644 --- a/ko/codes/cpp/chapter_stack_and_queue/queue.cpp +++ b/ko/codes/cpp/chapter_stack_and_queue/queue.cpp @@ -11,7 +11,7 @@ int main() { /* 큐 초기화 */ queue queue; - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -24,7 +24,7 @@ int main() { int front = queue.front(); cout << "맨 앞 원소 front = " << front << endl; - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ queue.pop(); cout << "큐에서 꺼낸 원소 front = " << front << ", 큐에서 꺼낸 후 queue = "; printQueue(queue); diff --git a/ko/codes/csharp/chapter_hashing/built_in_hash.cs b/ko/codes/csharp/chapter_hashing/built_in_hash.cs index 17a8bc035..b720e46d6 100644 --- a/ko/codes/csharp/chapter_hashing/built_in_hash.cs +++ b/ko/codes/csharp/chapter_hashing/built_in_hash.cs @@ -11,26 +11,26 @@ public class built_in_hash { public void Test() { int num = 3; int hashNum = num.GetHashCode(); - Console.WriteLine("정수 " + num + " ; 해시값: " + hashNum); + Console.WriteLine("정수 " + num + " → 해시값: " + hashNum); bool bol = true; int hashBol = bol.GetHashCode(); - Console.WriteLine("불리언 값 " + bol + " ; 해시값: " + hashBol); + Console.WriteLine("불리언 값 " + bol + " → 해시값: " + hashBol); double dec = 3.14159; int hashDec = dec.GetHashCode(); - Console.WriteLine("소수 " + dec + " ; 해시값: " + hashDec); + Console.WriteLine("소수 " + dec + " → 해시값: " + hashDec); string str = "Hello 算法"; int hashStr = str.GetHashCode(); - Console.WriteLine("문자열 " + str + " ; 해시값: " + hashStr); + Console.WriteLine("문자열 " + str + " → 해시값: " + hashStr); object[] arr = [12836, "小哈"]; int hashTup = arr.GetHashCode(); - Console.WriteLine("배열 [" + string.Join(", ", arr) + "]의 해시값: " + hashTup); + Console.WriteLine("배열 [" + string.Join(", ", arr) + "] → 해시값: " + hashTup); ListNode obj = new(0); int hashObj = obj.GetHashCode(); - Console.WriteLine("노드 객체 " + obj + " ; 해시값: " + hashObj); + Console.WriteLine("노드 객체 " + obj + " → 해시값: " + hashObj); } } diff --git a/ko/codes/csharp/chapter_stack_and_queue/array_deque.cs b/ko/codes/csharp/chapter_stack_and_queue/array_deque.cs index 371e9d397..07b9d0949 100644 --- a/ko/codes/csharp/chapter_stack_and_queue/array_deque.cs +++ b/ko/codes/csharp/chapter_stack_and_queue/array_deque.cs @@ -129,13 +129,13 @@ public class array_deque { int peekLast = deque.PeekLast(); Console.WriteLine("맨 뒤 원소 peekLast = " + peekLast); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.PushLast(4); Console.WriteLine("원소 4를 맨 뒤에 삽입한 후 deque = " + string.Join(" ", deque.ToArray())); deque.PushFirst(1); Console.WriteLine("원소 1을 맨 앞에 삽입한 후 deque = " + string.Join(" ", deque.ToArray())); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int popLast = deque.PopLast(); Console.WriteLine("맨 뒤에서 꺼낸 원소 = " + popLast + ", 맨 뒤에서 꺼낸 후 deque = " + string.Join(" ", deque.ToArray())); int popFirst = deque.PopFirst(); diff --git a/ko/codes/csharp/chapter_stack_and_queue/array_queue.cs b/ko/codes/csharp/chapter_stack_and_queue/array_queue.cs index 8654fca27..5eb763393 100644 --- a/ko/codes/csharp/chapter_stack_and_queue/array_queue.cs +++ b/ko/codes/csharp/chapter_stack_and_queue/array_queue.cs @@ -32,7 +32,7 @@ class ArrayQueue { return queSize == 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ public void Push(int num) { if (queSize == Capacity()) { Console.WriteLine("큐가 가득 찼다"); @@ -46,7 +46,7 @@ class ArrayQueue { queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ public int Pop() { int num = Peek(); // 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -80,7 +80,7 @@ public class array_queue { int capacity = 10; ArrayQueue queue = new(capacity); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.Push(1); queue.Push(3); queue.Push(2); @@ -92,7 +92,7 @@ public class array_queue { int peek = queue.Peek(); Console.WriteLine("맨 앞 원소 peek = " + peek); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int pop = queue.Pop(); Console.WriteLine("큐에서 꺼낸 원소 pop = " + pop + ", 큐에서 꺼낸 후 queue = " + string.Join(",", queue.ToArray())); @@ -108,7 +108,7 @@ public class array_queue { for (int i = 0; i < 10; i++) { queue.Push(i); queue.Pop(); - Console.WriteLine("반복 " + i + " 회에서 삽입 + 꺼내기를 수행한 후 queue = " + string.Join(",", queue.ToArray())); + Console.WriteLine("반복 " + i + " 회차에서 삽입 + 꺼내기를 수행한 후 queue = " + string.Join(",", queue.ToArray())); } } } diff --git a/ko/codes/csharp/chapter_stack_and_queue/deque.cs b/ko/codes/csharp/chapter_stack_and_queue/deque.cs index e4c5115e6..477810afd 100644 --- a/ko/codes/csharp/chapter_stack_and_queue/deque.cs +++ b/ko/codes/csharp/chapter_stack_and_queue/deque.cs @@ -13,7 +13,7 @@ public class deque { // C#에서는 연결 리스트 LinkedList를 덱으로 사용한다 LinkedList deque = new(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.AddLast(2); // 맨 뒤에 추가한다 deque.AddLast(5); deque.AddLast(4); @@ -27,7 +27,7 @@ public class deque { int? peekLast = deque.Last?.Value; // 맨 뒤 원소 Console.WriteLine("맨 뒤 원소 peekLast = " + peekLast); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ deque.RemoveFirst(); // 맨 앞 원소를 꺼낸다 Console.WriteLine("맨 앞 원소를 꺼낸 후 deque = " + string.Join(",", deque)); deque.RemoveLast(); // 맨 뒤 원소를 꺼낸다 diff --git a/ko/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs b/ko/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs index aa37f11e5..c194e8cef 100644 --- a/ko/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs +++ b/ko/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs @@ -33,7 +33,7 @@ public class LinkedListDeque { return Size() == 0; } - /* 큐 삽입 연산 */ + /* 원소 삽입 연산 */ void Push(int num, bool isFront) { ListNode node = new(num); // 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다 @@ -69,7 +69,7 @@ public class LinkedListDeque { Push(num, false); } - /* 큐에서 꺼내는 연산 */ + /* 원소를 꺼내는 연산 */ int? Pop(bool isFront) { if (IsEmpty()) throw new Exception(); @@ -156,13 +156,13 @@ public class linkedlist_deque { int? peekLast = deque.PeekLast(); Console.WriteLine("맨 뒤 원소 peekLast = " + peekLast); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.PushLast(4); Console.WriteLine("원소 4를 맨 뒤에 삽입한 후 deque = " + string.Join(" ", deque.ToArray())); deque.PushFirst(1); Console.WriteLine("원소 1을 맨 앞에 삽입한 후 deque = " + string.Join(" ", deque.ToArray())); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int? popLast = deque.PopLast(); Console.WriteLine("맨 뒤에서 꺼낸 원소 = " + popLast + ", 맨 뒤에서 꺼낸 후 deque = " + string.Join(" ", deque.ToArray())); int? popFirst = deque.PopFirst(); diff --git a/ko/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs b/ko/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs index eec778045..b464e9fc1 100644 --- a/ko/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs +++ b/ko/codes/csharp/chapter_stack_and_queue/linkedlist_queue.cs @@ -26,7 +26,7 @@ class LinkedListQueue { return Size() == 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ public void Push(int num) { // 꼬리 노드 뒤에 num을 추가한다 ListNode node = new(num); @@ -42,7 +42,7 @@ class LinkedListQueue { queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ public int Pop() { int num = Peek(); // 머리 노드를 삭제한다 @@ -79,7 +79,7 @@ public class linkedlist_queue { /* 큐 초기화 */ LinkedListQueue queue = new(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.Push(1); queue.Push(3); queue.Push(2); @@ -91,7 +91,7 @@ public class linkedlist_queue { int peek = queue.Peek(); Console.WriteLine("맨 앞 원소 peek = " + peek); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int pop = queue.Pop(); Console.WriteLine("큐에서 꺼낸 원소 pop = " + pop + ", 큐에서 꺼낸 후 queue = " + string.Join(",", queue.ToArray())); diff --git a/ko/codes/csharp/chapter_stack_and_queue/queue.cs b/ko/codes/csharp/chapter_stack_and_queue/queue.cs index 55bfd4da0..c2293b557 100644 --- a/ko/codes/csharp/chapter_stack_and_queue/queue.cs +++ b/ko/codes/csharp/chapter_stack_and_queue/queue.cs @@ -12,7 +12,7 @@ public class queue { /* 큐 초기화 */ Queue queue = new(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.Enqueue(1); queue.Enqueue(3); queue.Enqueue(2); @@ -24,7 +24,7 @@ public class queue { int peek = queue.Peek(); Console.WriteLine("맨 앞 원소 peek = " + peek); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int pop = queue.Dequeue(); Console.WriteLine("큐에서 꺼낸 원소 pop = " + pop + ", 큐에서 꺼낸 후 queue = " + string.Join(",", queue)); diff --git a/ko/codes/dart/chapter_hashing/built_in_hash.dart b/ko/codes/dart/chapter_hashing/built_in_hash.dart index 0f9910f90..fa52e211b 100644 --- a/ko/codes/dart/chapter_hashing/built_in_hash.dart +++ b/ko/codes/dart/chapter_hashing/built_in_hash.dart @@ -18,7 +18,7 @@ void main() { double dec = 3.14159; int hashDec = dec.hashCode; - print("소수 = $dec, 해시값 = $hashDec"); + print("소수 $dec → 해시값: $hashDec"); String str = "Hello 算法"; int hashStr = str.hashCode; @@ -26,9 +26,9 @@ void main() { List arr = [12836, "小哈"]; int hashArr = arr.hashCode; - print("배열 = $arr, 해시값 = $hashArr"); + print("배열 $arr → 해시값: $hashArr"); ListNode obj = new ListNode(0); int hashObj = obj.hashCode; - print("노드 객체 = $obj, 해시값 = $hashObj"); + print("노드 객체 $obj → 해시값: $hashObj"); } diff --git a/ko/codes/dart/chapter_hashing/hash_map.dart b/ko/codes/dart/chapter_hashing/hash_map.dart index eb362024e..d1f7d3231 100644 --- a/ko/codes/dart/chapter_hashing/hash_map.dart +++ b/ko/codes/dart/chapter_hashing/hash_map.dart @@ -36,6 +36,5 @@ void main() { print("\n키 Key만 순회"); map.keys.forEach((key) => print(key)); print("\n값 Value만 순회"); - map.forEach((key, value) => print("$value")); map.values.forEach((value) => print(value)); } diff --git a/ko/codes/dart/chapter_stack_and_queue/array_deque.dart b/ko/codes/dart/chapter_stack_and_queue/array_deque.dart index aecaf23cc..4460e84ee 100644 --- a/ko/codes/dart/chapter_stack_and_queue/array_deque.dart +++ b/ko/codes/dart/chapter_stack_and_queue/array_deque.dart @@ -124,13 +124,13 @@ void main() { final int peekLast = deque.peekLast(); print("맨 뒤 원소 peekLast = $peekLast"); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(4); print("맨 뒤에 원소 4를 삽입한 후 deque = ${deque.toArray()}"); deque.pushFirst(1); print("맨 앞에 원소 1을 삽입한 후 deque = ${deque.toArray()}"); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ final int popLast = deque.popLast(); print("맨 뒤에서 꺼낸 원소 = $popLast , 꺼낸 후 deque = ${deque.toArray()}"); final int popFirst = deque.popFirst(); diff --git a/ko/codes/dart/chapter_stack_and_queue/array_queue.dart b/ko/codes/dart/chapter_stack_and_queue/array_queue.dart index 8992583b4..dc740d555 100644 --- a/ko/codes/dart/chapter_stack_and_queue/array_queue.dart +++ b/ko/codes/dart/chapter_stack_and_queue/array_queue.dart @@ -30,7 +30,7 @@ class ArrayQueue { return _queSize == 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ void push(int _num) { if (_queSize == capaCity()) { throw Exception("큐가 가득 찼다"); @@ -43,7 +43,7 @@ class ArrayQueue { _queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ int pop() { int _num = peek(); // 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -77,7 +77,7 @@ void main() { final int capacity = 10; final ArrayQueue queue = ArrayQueue(capacity); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -89,7 +89,7 @@ void main() { final int peek = queue.peek(); print("맨 앞 원소 peek = $peek"); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ final int pop = queue.pop(); print("큐에서 꺼낸 원소 pop = $pop , 꺼낸 후 queue = ${queue.toArray()}"); @@ -105,6 +105,6 @@ void main() { for (int i = 0; i < 10; i++) { queue.push(i); queue.pop(); - print("반복 $i : 삽입 + 꺼내기 후 queue = ${queue.toArray()}"); + print("반복 $i 회차에서 삽입 + 꺼내기를 수행한 후 queue = ${queue.toArray()}"); } } diff --git a/ko/codes/dart/chapter_stack_and_queue/deque.dart b/ko/codes/dart/chapter_stack_and_queue/deque.dart index 8cc83a5b2..cd56b7a6f 100644 --- a/ko/codes/dart/chapter_stack_and_queue/deque.dart +++ b/ko/codes/dart/chapter_stack_and_queue/deque.dart @@ -20,13 +20,13 @@ void main() { final int peekLast = deque.last; print("맨 뒤 원소 peekLast = $peekLast"); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.addLast(4); print("맨 뒤에 원소 4를 삽입한 후 deque = $deque"); deque.addFirst(1); print("맨 앞에 원소 1을 삽입한 후 deque = $deque"); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ final int popLast = deque.removeLast(); print("맨 뒤에서 꺼낸 원소 = $popLast , 꺼낸 후 deque = $deque"); final int popFirst = deque.removeFirst(); diff --git a/ko/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart b/ko/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart index 9a75a8775..69870f7d1 100644 --- a/ko/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart +++ b/ko/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart @@ -34,7 +34,7 @@ class LinkedListDeque { return size() == 0; } - /* 큐 삽입 연산 */ + /* 원소 삽입 연산 */ void push(int _num, bool isFront) { final ListNode node = ListNode(_num); if (isEmpty()) { @@ -66,7 +66,7 @@ class LinkedListDeque { push(_num, false); } - /* 큐에서 꺼내는 연산 */ + /* 원소를 꺼내는 연산 */ int? pop(bool isFront) { // 큐가 비어 있으면 바로 null을 반환한다 if (isEmpty()) { @@ -147,13 +147,13 @@ void main() { int? peekLast = deque.peekLast(); print("맨 뒤 원소 peekLast = $peekLast"); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(4); print("맨 뒤에 원소 4를 삽입한 후 deque = ${deque.toArray()}"); deque.pushFirst(1); print("맨 앞에 원소 1을 삽입한 후 deque = ${deque.toArray()}"); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int? popLast = deque.popLast(); print("맨 뒤에서 꺼낸 원소 = $popLast , 꺼낸 후 deque = ${deque.toArray()}"); int? popFirst = deque.popFirst(); diff --git a/ko/codes/dart/chapter_stack_and_queue/linkedlist_queue.dart b/ko/codes/dart/chapter_stack_and_queue/linkedlist_queue.dart index 0e97b4d12..78a2bb8ed 100644 --- a/ko/codes/dart/chapter_stack_and_queue/linkedlist_queue.dart +++ b/ko/codes/dart/chapter_stack_and_queue/linkedlist_queue.dart @@ -27,7 +27,7 @@ class LinkedListQueue { return _queSize == 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ void push(int _num) { // 꼬리 노드 뒤에 _num을 추가한다 final node = ListNode(_num); @@ -43,7 +43,7 @@ class LinkedListQueue { _queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ int pop() { final int _num = peek(); // 머리 노드를 삭제한다 @@ -77,7 +77,7 @@ void main() { /* 큐 초기화 */ final queue = LinkedListQueue(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -89,7 +89,7 @@ void main() { final int peek = queue.peek(); print("맨 앞 원소 peek = $peek"); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ final int pop = queue.pop(); print("큐에서 꺼낸 원소 pop = $pop , 꺼낸 후 queue = ${queue.toArray()}"); diff --git a/ko/codes/dart/chapter_stack_and_queue/queue.dart b/ko/codes/dart/chapter_stack_and_queue/queue.dart index 2f12a228c..8998c2391 100644 --- a/ko/codes/dart/chapter_stack_and_queue/queue.dart +++ b/ko/codes/dart/chapter_stack_and_queue/queue.dart @@ -11,7 +11,7 @@ void main() { // Dart에서는 일반적으로 덱 클래스 Queue를 큐로 사용한다 final Queue queue = Queue(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.add(1); queue.add(3); queue.add(2); @@ -23,7 +23,7 @@ void main() { final int peek = queue.first; print("맨 앞 원소 peek = $peek"); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ final int pop = queue.removeFirst(); print("큐에서 꺼낸 원소 pop = $pop , 꺼낸 후 queue = $queue"); diff --git a/ko/codes/dart/chapter_tree/binary_tree.dart b/ko/codes/dart/chapter_tree/binary_tree.dart index b073a657a..7286b399a 100644 --- a/ko/codes/dart/chapter_tree/binary_tree.dart +++ b/ko/codes/dart/chapter_tree/binary_tree.dart @@ -9,7 +9,7 @@ import '../utils/tree_node.dart'; void main() { /* 이진 트리 초기화 */ - // 노드를 초기화한다 + // 노드 초기화 TreeNode n1 = TreeNode(1); TreeNode n2 = TreeNode(2); TreeNode n3 = TreeNode(3); diff --git a/ko/codes/go/chapter_heap/heap_test.go b/ko/codes/go/chapter_heap/heap_test.go index 247e3dc79..fc9781363 100644 --- a/ko/codes/go/chapter_heap/heap_test.go +++ b/ko/codes/go/chapter_heap/heap_test.go @@ -91,8 +91,6 @@ func TestMyHeap(t *testing.T) { } func TestTopKHeap(t *testing.T) { - /* 힙 초기화 */ - // 최대 힙 초기화 nums := []int{1, 7, 6, 3, 2} k := 3 res := topKHeap(nums, k) diff --git a/ko/codes/go/chapter_stack_and_queue/array_queue.go b/ko/codes/go/chapter_stack_and_queue/array_queue.go index 0ac74f742..56300d3ef 100644 --- a/ko/codes/go/chapter_stack_and_queue/array_queue.go +++ b/ko/codes/go/chapter_stack_and_queue/array_queue.go @@ -32,7 +32,7 @@ func (q *arrayQueue) isEmpty() bool { return q.queSize == 0 } -/* 큐에 삽입 */ +/* 원소 삽입 */ func (q *arrayQueue) push(num int) { // rear == queCapacity이면 큐가 가득 찼음을 나타낸다 if q.queSize == q.queCapacity { @@ -46,7 +46,7 @@ func (q *arrayQueue) push(num int) { q.queSize++ } -/* 큐에서 꺼내기 */ +/* 원소 꺼내기 */ func (q *arrayQueue) pop() any { num := q.peek() if num == nil { diff --git a/ko/codes/go/chapter_stack_and_queue/deque_test.go b/ko/codes/go/chapter_stack_and_queue/deque_test.go index 452310a22..95f75731f 100644 --- a/ko/codes/go/chapter_stack_and_queue/deque_test.go +++ b/ko/codes/go/chapter_stack_and_queue/deque_test.go @@ -17,7 +17,7 @@ func TestDeque(t *testing.T) { // Go에서는 list를 덱으로 사용한다 deque := list.New() - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.PushBack(2) deque.PushBack(5) deque.PushBack(4) @@ -32,7 +32,7 @@ func TestDeque(t *testing.T) { rear := deque.Back() fmt.Println("맨 뒤 원소 rear =", rear.Value) - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ deque.Remove(front) fmt.Print("맨 앞에서 꺼낸 원소 front = ", front.Value, ", 맨 앞에서 꺼낸 후 deque = ") PrintList(deque) @@ -51,10 +51,9 @@ func TestDeque(t *testing.T) { func TestArrayDeque(t *testing.T) { /* 덱 초기화 */ - // Go에서는 list를 덱으로 사용한다 deque := newArrayDeque(16) - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(3) deque.pushLast(2) deque.pushLast(5) @@ -67,7 +66,7 @@ func TestArrayDeque(t *testing.T) { peekLast := deque.peekLast() fmt.Println("맨 뒤 원소 peekLast =", peekLast) - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(4) fmt.Print("원소 4를 맨 뒤에 삽입한 후 deque = ") PrintSlice(deque.toSlice()) @@ -75,7 +74,7 @@ func TestArrayDeque(t *testing.T) { fmt.Print("원소 1을 맨 앞에 삽입한 후 deque = ") PrintSlice(deque.toSlice()) - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ popFirst := deque.popFirst() fmt.Print("맨 앞에서 꺼낸 원소 popFirst = ", popFirst, ", 맨 앞에서 꺼낸 후 deque = ") PrintSlice(deque.toSlice()) @@ -96,13 +95,13 @@ func TestLinkedListDeque(t *testing.T) { // 큐 초기화 deque := newLinkedListDeque() - // 큐에 원소 삽입 + // 원소 삽입 deque.pushLast(2) deque.pushLast(5) deque.pushLast(4) deque.pushFirst(3) deque.pushFirst(1) - fmt.Print("큐 deque = ") + fmt.Print("덱 deque = ") PrintList(deque.toList()) // 맨 앞 원소 접근 @@ -111,7 +110,7 @@ func TestLinkedListDeque(t *testing.T) { rear := deque.peekLast() fmt.Println("맨 뒤 원소 rear =", rear) - // 큐에서 원소 꺼내기 + // 원소 꺼내기 popFirst := deque.popFirst() fmt.Print("맨 앞에서 꺼낸 원소 popFirst = ", popFirst, ", 맨 앞에서 꺼낸 후 deque = ") PrintList(deque.toList()) diff --git a/ko/codes/go/chapter_stack_and_queue/linkedlist_queue.go b/ko/codes/go/chapter_stack_and_queue/linkedlist_queue.go index 7968564c6..f11ce4ceb 100644 --- a/ko/codes/go/chapter_stack_and_queue/linkedlist_queue.go +++ b/ko/codes/go/chapter_stack_and_queue/linkedlist_queue.go @@ -21,12 +21,12 @@ func newLinkedListQueue() *linkedListQueue { } } -/* 큐에 삽입 */ +/* 원소 삽입 */ func (s *linkedListQueue) push(value any) { s.data.PushBack(value) } -/* 큐에서 꺼내기 */ +/* 원소 꺼내기 */ func (s *linkedListQueue) pop() any { if s.isEmpty() { return nil diff --git a/ko/codes/go/chapter_stack_and_queue/queue_test.go b/ko/codes/go/chapter_stack_and_queue/queue_test.go index b7de5ac37..951038391 100644 --- a/ko/codes/go/chapter_stack_and_queue/queue_test.go +++ b/ko/codes/go/chapter_stack_and_queue/queue_test.go @@ -17,7 +17,7 @@ func TestQueue(t *testing.T) { // Go에서는 list를 큐로 사용한다 queue := list.New() - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.PushBack(1) queue.PushBack(3) queue.PushBack(2) @@ -30,7 +30,7 @@ func TestQueue(t *testing.T) { peek := queue.Front() fmt.Println("맨 앞 원소 peek =", peek.Value) - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ pop := queue.Front() queue.Remove(pop) fmt.Print("큐에서 꺼낸 원소 pop = ", pop.Value, ", 큐에서 꺼낸 후 queue = ") @@ -54,7 +54,7 @@ func TestArrayQueue(t *testing.T) { t.Errorf("기대값:%v,실제값:%v", nil, queue.pop()) } - // 큐에 원소 삽입 + // 원소 삽입 queue.push(1) queue.push(3) queue.push(2) @@ -67,7 +67,7 @@ func TestArrayQueue(t *testing.T) { peek := queue.peek() fmt.Println("맨 앞 원소 peek =", peek) - // 큐에서 원소 꺼내기 + // 원소 꺼내기 pop := queue.pop() fmt.Print("큐에서 꺼낸 원소 pop = ", pop, ", 꺼낸 뒤 queue = ") PrintSlice(queue.toSlice()) @@ -84,7 +84,7 @@ func TestArrayQueue(t *testing.T) { for i := 0; i < 10; i++ { queue.push(i) queue.pop() - fmt.Print("반복", i, "회에서 삽입 + 꺼내기를 수행한 후 queue =") + fmt.Print("반복 ", i, " 회차에서 삽입 + 꺼내기를 수행한 후 queue =") PrintSlice(queue.toSlice()) } } @@ -93,7 +93,7 @@ func TestLinkedListQueue(t *testing.T) { // 큐 초기화 queue := newLinkedListQueue() - // 큐에 원소 삽입 + // 원소 삽입 queue.push(1) queue.push(3) queue.push(2) @@ -106,7 +106,7 @@ func TestLinkedListQueue(t *testing.T) { peek := queue.peek() fmt.Println("맨 앞 원소 peek =", peek) - // 큐에서 원소 꺼내기 + // 원소 꺼내기 pop := queue.pop() fmt.Print("큐에서 꺼낸 원소 pop = ", pop, ", 꺼낸 뒤 queue = ") PrintList(queue.toList()) diff --git a/ko/codes/java/chapter_array_and_linkedlist/list.java b/ko/codes/java/chapter_array_and_linkedlist/list.java index d5f1b9b42..02ac5a62e 100644 --- a/ko/codes/java/chapter_array_and_linkedlist/list.java +++ b/ko/codes/java/chapter_array_and_linkedlist/list.java @@ -11,7 +11,7 @@ import java.util.*; public class list { public static void main(String[] args) { /* 리스트 초기화 */ - // 배열의 원소 형식에는 int[]의 래퍼 형식인 Integer[]를 사용한다는 점에 주의한다 + // 리스트 원소는 int의 래퍼 클래스인 Integer만 사용할 수 있으므로 배열 타입은 int[]가 아닌 Integer[]여야 한다는 점에 유의한다 Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); System.out.println("리스트 nums = " + nums); diff --git a/ko/codes/java/chapter_hashing/built_in_hash.java b/ko/codes/java/chapter_hashing/built_in_hash.java index 476af0359..c01ee88c4 100644 --- a/ko/codes/java/chapter_hashing/built_in_hash.java +++ b/ko/codes/java/chapter_hashing/built_in_hash.java @@ -13,26 +13,26 @@ public class built_in_hash { public static void main(String[] args) { int num = 3; int hashNum = Integer.hashCode(num); - System.out.println("정수 " + num + " ; 해시값: " + hashNum); + System.out.println("정수 " + num + " → 해시값: " + hashNum); boolean bol = true; int hashBol = Boolean.hashCode(bol); - System.out.println("불리언 값 " + bol + " ; 해시값: " + hashBol); + System.out.println("불리언 값 " + bol + " → 해시값: " + hashBol); double dec = 3.14159; int hashDec = Double.hashCode(dec); - System.out.println("소수 " + dec + " ; 해시값: " + hashDec); + System.out.println("소수 " + dec + " → 해시값: " + hashDec); String str = "Hello 算法"; int hashStr = str.hashCode(); - System.out.println("문자열 " + str + " ; 해시값: " + hashStr); + System.out.println("문자열 " + str + " → 해시값: " + hashStr); Object[] arr = { 12836, "小哈" }; int hashTup = Arrays.hashCode(arr); - System.out.println("배열 " + Arrays.toString(arr) + " ; 해시값: " + hashTup); + System.out.println("배열 " + Arrays.toString(arr) + " → 해시값: " + hashTup); ListNode obj = new ListNode(0); int hashObj = obj.hashCode(); - System.out.println("노드 객체 " + obj + " ; 해시값: " + hashObj); + System.out.println("노드 객체 " + obj + " → 해시값: " + hashObj); } } diff --git a/ko/codes/java/chapter_stack_and_queue/array_deque.java b/ko/codes/java/chapter_stack_and_queue/array_deque.java index 095a5a480..3dc0198ae 100644 --- a/ko/codes/java/chapter_stack_and_queue/array_deque.java +++ b/ko/codes/java/chapter_stack_and_queue/array_deque.java @@ -128,13 +128,13 @@ public class array_deque { int peekLast = deque.peekLast(); System.out.println("맨 뒤 원소 peekLast = " + peekLast); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(4); System.out.println("원소 4를 맨 뒤에 삽입한 후 deque = " + Arrays.toString(deque.toArray())); deque.pushFirst(1); System.out.println("원소 1을 맨 앞에 삽입한 후 deque = " + Arrays.toString(deque.toArray())); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int popLast = deque.popLast(); System.out.println("맨 뒤에서 꺼낸 원소 = " + popLast + ", 맨 뒤에서 꺼낸 후 deque = " + Arrays.toString(deque.toArray())); int popFirst = deque.popFirst(); diff --git a/ko/codes/java/chapter_stack_and_queue/array_queue.java b/ko/codes/java/chapter_stack_and_queue/array_queue.java index 55b8bff3b..f70a525dd 100644 --- a/ko/codes/java/chapter_stack_and_queue/array_queue.java +++ b/ko/codes/java/chapter_stack_and_queue/array_queue.java @@ -34,7 +34,7 @@ class ArrayQueue { return queSize == 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ public void push(int num) { if (queSize == capacity()) { System.out.println("큐가 가득 찼다"); @@ -48,7 +48,7 @@ class ArrayQueue { queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ public int pop() { int num = peek(); // 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -81,7 +81,7 @@ public class array_queue { int capacity = 10; ArrayQueue queue = new ArrayQueue(capacity); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -93,7 +93,7 @@ public class array_queue { int peek = queue.peek(); System.out.println("맨 앞 원소 peek = " + peek); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int pop = queue.pop(); System.out.println("큐에서 꺼낸 원소 pop = " + pop + ", 큐에서 꺼낸 후 queue = " + Arrays.toString(queue.toArray())); @@ -109,7 +109,7 @@ public class array_queue { for (int i = 0; i < 10; i++) { queue.push(i); queue.pop(); - System.out.println("반복 " + i + " 회에서 삽입 + 꺼내기를 수행한 후 queue = " + Arrays.toString(queue.toArray())); + System.out.println("반복 " + i + " 회차에서 삽입 + 꺼내기를 수행한 후 queue = " + Arrays.toString(queue.toArray())); } } } diff --git a/ko/codes/java/chapter_stack_and_queue/deque.java b/ko/codes/java/chapter_stack_and_queue/deque.java index 78dc4a35a..8213090ee 100644 --- a/ko/codes/java/chapter_stack_and_queue/deque.java +++ b/ko/codes/java/chapter_stack_and_queue/deque.java @@ -23,13 +23,13 @@ public class deque { int peekLast = deque.peekLast(); System.out.println("맨 뒤 원소 peekLast = " + peekLast); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.offerLast(4); System.out.println("원소 4를 맨 뒤에 삽입한 후 deque = " + deque); deque.offerFirst(1); System.out.println("원소 1을 맨 앞에 삽입한 후 deque = " + deque); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int popLast = deque.pollLast(); System.out.println("맨 뒤에서 꺼낸 원소 = " + popLast + ", 맨 뒤에서 꺼낸 후 deque = " + deque); int popFirst = deque.pollFirst(); diff --git a/ko/codes/java/chapter_stack_and_queue/linkedlist_deque.java b/ko/codes/java/chapter_stack_and_queue/linkedlist_deque.java index ee7213e16..81f356bf7 100644 --- a/ko/codes/java/chapter_stack_and_queue/linkedlist_deque.java +++ b/ko/codes/java/chapter_stack_and_queue/linkedlist_deque.java @@ -39,7 +39,7 @@ class LinkedListDeque { return size() == 0; } - /* 큐 삽입 연산 */ + /* 원소 삽입 연산 */ private void push(int num, boolean isFront) { ListNode node = new ListNode(num); // 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다 @@ -71,7 +71,7 @@ class LinkedListDeque { push(num, false); } - /* 큐에서 꺼내는 연산 */ + /* 원소를 꺼내는 연산 */ private int pop(boolean isFront) { if (isEmpty()) throw new IndexOutOfBoundsException(); @@ -154,13 +154,13 @@ public class linkedlist_deque { int peekLast = deque.peekLast(); System.out.println("맨 뒤 원소 peekLast = " + peekLast); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(4); System.out.println("원소 4를 맨 뒤에 삽입한 후 deque = " + Arrays.toString(deque.toArray())); deque.pushFirst(1); System.out.println("원소 1을 맨 앞에 삽입한 후 deque = " + Arrays.toString(deque.toArray())); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int popLast = deque.popLast(); System.out.println("맨 뒤에서 꺼낸 원소 = " + popLast + ", 맨 뒤에서 꺼낸 후 deque = " + Arrays.toString(deque.toArray())); int popFirst = deque.popFirst(); diff --git a/ko/codes/java/chapter_stack_and_queue/linkedlist_queue.java b/ko/codes/java/chapter_stack_and_queue/linkedlist_queue.java index 6680af207..604f14546 100644 --- a/ko/codes/java/chapter_stack_and_queue/linkedlist_queue.java +++ b/ko/codes/java/chapter_stack_and_queue/linkedlist_queue.java @@ -28,7 +28,7 @@ class LinkedListQueue { return size() == 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ public void push(int num) { // 꼬리 노드 뒤에 num을 추가한다 ListNode node = new ListNode(num); @@ -44,7 +44,7 @@ class LinkedListQueue { queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ public int pop() { int num = peek(); // 머리 노드를 삭제한다 @@ -77,7 +77,7 @@ public class linkedlist_queue { /* 큐 초기화 */ LinkedListQueue queue = new LinkedListQueue(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -89,7 +89,7 @@ public class linkedlist_queue { int peek = queue.peek(); System.out.println("맨 앞 원소 peek = " + peek); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int pop = queue.pop(); System.out.println("큐에서 꺼낸 원소 pop = " + pop + ", 큐에서 꺼낸 후 queue = " + Arrays.toString(queue.toArray())); diff --git a/ko/codes/java/chapter_stack_and_queue/queue.java b/ko/codes/java/chapter_stack_and_queue/queue.java index d0fa104c4..bf1238ba3 100644 --- a/ko/codes/java/chapter_stack_and_queue/queue.java +++ b/ko/codes/java/chapter_stack_and_queue/queue.java @@ -13,7 +13,7 @@ public class queue { /* 큐 초기화 */ Queue queue = new LinkedList<>(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.offer(1); queue.offer(3); queue.offer(2); @@ -25,7 +25,7 @@ public class queue { int peek = queue.peek(); System.out.println("맨 앞 원소 peek = " + peek); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ int pop = queue.poll(); System.out.println("큐에서 꺼낸 원소 pop = " + pop + ", 큐에서 꺼낸 후 queue = " + queue); diff --git a/ko/codes/javascript/chapter_stack_and_queue/array_deque.js b/ko/codes/javascript/chapter_stack_and_queue/array_deque.js index 288c7fc30..56a544a99 100644 --- a/ko/codes/javascript/chapter_stack_and_queue/array_deque.js +++ b/ko/codes/javascript/chapter_stack_and_queue/array_deque.js @@ -123,13 +123,13 @@ console.log('맨 앞 원소 peekFirst = ' + peekFirst); const peekLast = deque.peekLast(); console.log('맨 뒤 원소 peekLast = ' + peekLast); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ deque.pushLast(4); console.log('뒤쪽에 원소 4를 삽입한 후 deque = [' + deque.toArray() + ']'); deque.pushFirst(1); console.log('앞쪽에 원소 1을 삽입한 후 deque = [' + deque.toArray() + ']'); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ const popLast = deque.popLast(); console.log( '맨 뒤에서 꺼낸 원소 = ' + diff --git a/ko/codes/javascript/chapter_stack_and_queue/array_queue.js b/ko/codes/javascript/chapter_stack_and_queue/array_queue.js index ed1c13bf1..e5cf8197e 100644 --- a/ko/codes/javascript/chapter_stack_and_queue/array_queue.js +++ b/ko/codes/javascript/chapter_stack_and_queue/array_queue.js @@ -29,7 +29,7 @@ class ArrayQueue { return this.#queSize === 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ push(num) { if (this.size === this.capacity) { console.log('큐가 가득 찼다'); @@ -43,7 +43,7 @@ class ArrayQueue { this.#queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ pop() { const num = this.peek(); // 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -74,7 +74,7 @@ class ArrayQueue { const capacity = 10; const queue = new ArrayQueue(capacity); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -86,7 +86,7 @@ console.log('큐 queue =', queue.toArray()); const peek = queue.peek(); console.log('맨 앞 원소 peek = ' + peek); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ const pop = queue.pop(); console.log('큐에서 꺼낸 원소 pop = ' + pop + ', 큐에서 꺼낸 후 queue =', queue.toArray()); @@ -102,5 +102,5 @@ console.log('큐가 비어 있는가 = ' + isEmpty); for (let i = 0; i < 10; i++) { queue.push(i); queue.pop(); - console.log('반복 ' + i + ' 회에서 삽입 + 꺼내기를 수행한 후 queue =', queue.toArray()); + console.log('반복 ' + i + ' 회차에서 삽입 + 꺼내기를 수행한 후 queue =', queue.toArray()); } diff --git a/ko/codes/javascript/chapter_stack_and_queue/deque.js b/ko/codes/javascript/chapter_stack_and_queue/deque.js index 0f781c6b5..09026e4f3 100644 --- a/ko/codes/javascript/chapter_stack_and_queue/deque.js +++ b/ko/codes/javascript/chapter_stack_and_queue/deque.js @@ -6,10 +6,10 @@ /* 실행 코드 */ /* 덱 초기화 */ -// JavaScript에는 내장 덱이 없으므로 Array를 덱으로 사용한다 +// JavaScript에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 const deque = []; -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ deque.push(2); deque.push(5); deque.push(4); @@ -24,7 +24,7 @@ console.log('맨 앞 원소 peekFirst = ' + peekFirst); const peekLast = deque[deque.length - 1]; console.log('맨 뒤 원소 peekLast = ' + peekLast); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ // 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 유의한다 const popFront = deque.shift(); console.log( diff --git a/ko/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js b/ko/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js index 4fb640757..7528e2451 100644 --- a/ko/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js +++ b/ko/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js @@ -152,7 +152,7 @@ console.log('맨 앞 원소 peekFirst = ' + peekFirst); const peekLast = linkedListDeque.peekLast(); console.log('맨 뒤 원소 peekLast = ' + peekLast); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ linkedListDeque.pushLast(4); console.log('뒤쪽에 원소 4를 삽입한 후 linkedListDeque = '); linkedListDeque.print(); @@ -160,7 +160,7 @@ linkedListDeque.pushFirst(1); console.log('앞쪽에 원소 1을 삽입한 후 linkedListDeque = '); linkedListDeque.print(); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ const popLast = linkedListDeque.popLast(); console.log('맨 뒤에서 꺼낸 원소 = ' + popLast + ', 뒤쪽 원소를 꺼낸 후 linkedListDeque = '); linkedListDeque.print(); diff --git a/ko/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js b/ko/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js index 66f77a778..12cd0602c 100644 --- a/ko/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js +++ b/ko/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js @@ -27,7 +27,7 @@ class LinkedListQueue { return this.size === 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ push(num) { // 꼬리 노드 뒤에 num을 추가한다 const node = new ListNode(num); @@ -43,7 +43,7 @@ class LinkedListQueue { this.#queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ pop() { const num = this.peek(); // 머리 노드를 삭제한다 @@ -74,7 +74,7 @@ class LinkedListQueue { /* 큐 초기화 */ const queue = new LinkedListQueue(); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -86,7 +86,7 @@ console.log('큐 queue = ' + queue.toArray()); const peek = queue.peek(); console.log('맨 앞 원소 peek = ' + peek); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ const pop = queue.pop(); console.log('큐에서 꺼낸 원소 pop = ' + pop + ', 큐에서 꺼낸 후 queue = ' + queue.toArray()); diff --git a/ko/codes/javascript/chapter_stack_and_queue/queue.js b/ko/codes/javascript/chapter_stack_and_queue/queue.js index 0a8938d73..44903ee38 100644 --- a/ko/codes/javascript/chapter_stack_and_queue/queue.js +++ b/ko/codes/javascript/chapter_stack_and_queue/queue.js @@ -9,7 +9,7 @@ // JavaScript에는 내장 큐가 없으므로 Array를 큐로 사용할 수 있다 const queue = []; -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -21,7 +21,7 @@ console.log('큐 queue =', queue); const peek = queue[0]; console.log('맨 앞 원소 peek =', peek); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ // 내부 자료 구조가 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 const pop = queue.shift(); console.log('큐에서 꺼낸 원소 pop =', pop, ', 큐에서 꺼낸 후 queue = ', queue); diff --git a/ko/codes/kotlin/chapter_hashing/built_in_hash.kt b/ko/codes/kotlin/chapter_hashing/built_in_hash.kt index 09f0ce4e9..3944ef752 100644 --- a/ko/codes/kotlin/chapter_hashing/built_in_hash.kt +++ b/ko/codes/kotlin/chapter_hashing/built_in_hash.kt @@ -12,15 +12,15 @@ import utils.ListNode fun main() { val num = 3 val hashNum = num.hashCode() - println("정수 = $num, 해시값 = $hashNum") + println("정수 $num → 해시값: $hashNum") val bol = true val hashBol = bol.hashCode() - println("불리언 값 = $bol, 해시값 = $hashBol") + println("불리언 값 $bol → 해시값: $hashBol") val dec = 3.14159 val hashDec = dec.hashCode() - println("소수 = $dec, 해시값 = $hashDec") + println("소수 $dec → 해시값: $hashDec") val str = "Hello 算法" val hashStr = str.hashCode() @@ -32,5 +32,5 @@ fun main() { val obj = ListNode(0) val hashObj = obj.hashCode() - println("노드 객체 = $obj, 해시값 = $hashObj") + println("노드 객체 $obj → 해시값: $hashObj") } \ No newline at end of file diff --git a/ko/codes/kotlin/chapter_stack_and_queue/array_deque.kt b/ko/codes/kotlin/chapter_stack_and_queue/array_deque.kt index adde5e8d3..bd2ef2f6d 100644 --- a/ko/codes/kotlin/chapter_stack_and_queue/array_deque.kt +++ b/ko/codes/kotlin/chapter_stack_and_queue/array_deque.kt @@ -123,13 +123,13 @@ fun main() { val peekLast = deque.peekLast() println("맨 뒤 원소 peekLast = $peekLast") - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(4) println("맨 뒤에 원소 4를 삽입한 후 deque = ${deque.toArray().contentToString()}") deque.pushFirst(1) println("맨 앞에 원소 1을 삽입한 후 deque = ${deque.toArray().contentToString()}") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ val popLast = deque.popLast() println("맨 뒤에서 꺼낸 원소 = ${popLast}, 꺼낸 후 deque = ${deque.toArray().contentToString()}") val popFirst = deque.popFirst() diff --git a/ko/codes/kotlin/chapter_stack_and_queue/array_queue.kt b/ko/codes/kotlin/chapter_stack_and_queue/array_queue.kt index 8a4e59fe1..3371db338 100644 --- a/ko/codes/kotlin/chapter_stack_and_queue/array_queue.kt +++ b/ko/codes/kotlin/chapter_stack_and_queue/array_queue.kt @@ -27,7 +27,7 @@ class ArrayQueue(capacity: Int) { return queSize == 0 } - /* 큐에 삽입 */ + /* 원소 삽입 */ fun push(num: Int) { if (queSize == capacity()) { println("큐가 가득 찼다") @@ -41,7 +41,7 @@ class ArrayQueue(capacity: Int) { queSize++ } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ fun pop(): Int { val num = peek() // 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -77,7 +77,7 @@ fun main() { val capacity = 10 val queue = ArrayQueue(capacity) - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(1) queue.push(3) queue.push(2) @@ -89,7 +89,7 @@ fun main() { val peek = queue.peek() println("맨 앞 원소 peek = $peek") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ val pop = queue.pop() println("큐에서 꺼낸 원소 pop = ${pop}, 꺼낸 후 queue = ${queue.toArray().contentToString()}") @@ -105,6 +105,6 @@ fun main() { for (i in 0..9) { queue.push(i) queue.pop() - println("반복 $i : 삽입 + 꺼내기 후 queue = ${queue.toArray().contentToString()}") + println("반복 $i 회차에서 삽입 + 꺼내기를 수행한 후 queue = ${queue.toArray().contentToString()}") } } \ No newline at end of file diff --git a/ko/codes/kotlin/chapter_stack_and_queue/deque.kt b/ko/codes/kotlin/chapter_stack_and_queue/deque.kt index 3c504717e..fbe502a76 100644 --- a/ko/codes/kotlin/chapter_stack_and_queue/deque.kt +++ b/ko/codes/kotlin/chapter_stack_and_queue/deque.kt @@ -23,13 +23,13 @@ fun main() { val peekLast = deque.peekLast() println("맨 뒤 원소 peekLast = $peekLast") - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.offerLast(4) println("맨 뒤에 원소 4를 삽입한 후 deque = $deque") deque.offerFirst(1) println("맨 앞에 원소 1을 삽입한 후 deque = $deque") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ val popLast = deque.pollLast() println("맨 뒤에서 꺼낸 원소 = $popLast, 꺼낸 후 deque = $deque") val popFirst = deque.pollFirst() diff --git a/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt b/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt index 62b8e55f9..bbf2c79e5 100644 --- a/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt +++ b/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt @@ -29,7 +29,7 @@ class LinkedListDeque { return size() == 0 } - /* 큐 삽입 연산 */ + /* 원소 삽입 연산 */ fun push(num: Int, isFront: Boolean) { val node = ListNode(num) // 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다 @@ -62,7 +62,7 @@ class LinkedListDeque { push(num, false) } - /* 큐에서 꺼내는 연산 */ + /* 원소를 꺼내는 연산 */ fun pop(isFront: Boolean): Int { if (isEmpty()) throw IndexOutOfBoundsException() @@ -143,13 +143,13 @@ fun main() { val peekLast = deque.peekLast() println("맨 뒤 원소 peekLast = $peekLast") - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(4) println("맨 뒤에 원소 4를 삽입한 후 deque = ${deque.toArray().contentToString()}") deque.pushFirst(1) println("맨 앞에 원소 1을 삽입한 후 deque = ${deque.toArray().contentToString()}") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ val popLast = deque.popLast() println("맨 뒤에서 꺼낸 원소 = ${popLast}, 꺼낸 후 deque = ${deque.toArray().contentToString()}") val popFirst = deque.popFirst() diff --git a/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_queue.kt b/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_queue.kt index 291f2e5f6..5fc189be2 100644 --- a/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_queue.kt +++ b/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_queue.kt @@ -24,7 +24,7 @@ class LinkedListQueue( return size() == 0 } - /* 큐에 삽입 */ + /* 원소 삽입 */ fun push(num: Int) { // 꼬리 노드 뒤에 num을 추가한다 val node = ListNode(num) @@ -40,7 +40,7 @@ class LinkedListQueue( queSize++ } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ fun pop(): Int { val num = peek() // 머리 노드를 삭제한다 @@ -72,7 +72,7 @@ fun main() { /* 큐 초기화 */ val queue = LinkedListQueue() - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(1) queue.push(3) queue.push(2) @@ -84,7 +84,7 @@ fun main() { val peek = queue.peek() println("맨 앞 원소 peek = $peek") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ val pop = queue.pop() println("큐에서 꺼낸 원소 pop = $pop, 꺼낸 후 queue = ${queue.toArray().contentToString()}") diff --git a/ko/codes/kotlin/chapter_stack_and_queue/queue.kt b/ko/codes/kotlin/chapter_stack_and_queue/queue.kt index c4bdf1893..e1e1e5efa 100644 --- a/ko/codes/kotlin/chapter_stack_and_queue/queue.kt +++ b/ko/codes/kotlin/chapter_stack_and_queue/queue.kt @@ -13,7 +13,7 @@ fun main() { /* 큐 초기화 */ val queue = LinkedList() - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.offer(1) queue.offer(3) queue.offer(2) @@ -25,7 +25,7 @@ fun main() { val peek = queue.peek() println("맨 앞 원소 peek = $peek") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ val pop = queue.poll() println("큐에서 꺼낸 원소 pop = $pop, 꺼낸 후 queue = $queue") diff --git a/ko/codes/python/chapter_hashing/built_in_hash.py b/ko/codes/python/chapter_hashing/built_in_hash.py index 6a777313c..28ff0d4d1 100644 --- a/ko/codes/python/chapter_hashing/built_in_hash.py +++ b/ko/codes/python/chapter_hashing/built_in_hash.py @@ -14,15 +14,15 @@ from modules import ListNode if __name__ == "__main__": num = 3 hash_num = hash(num) - print(f"정수 {num}의 해시값은 {hash_num}이다") + print(f"정수 {num} → 해시값: {hash_num}") bol = True hash_bol = hash(bol) - print(f"불리언 {bol}의 해시값은 {hash_bol}이다") + print(f"불리언 값 {bol} → 해시값: {hash_bol}") dec = 3.14159 hash_dec = hash(dec) - print(f"소수 {dec}의 해시값은 {hash_dec}이다") + print(f"소수 {dec} → 해시값: {hash_dec}") str = "Hello 算法" hash_str = hash(str) @@ -30,8 +30,8 @@ if __name__ == "__main__": tup = (12836, "小哈") hash_tup = hash(tup) - print(f"튜플 {tup}의 해시값은 {hash(hash_tup)}이다") + print(f"튜플 {tup} → 해시값: {hash_tup}") obj = ListNode(0) hash_obj = hash(obj) - print(f"노드 객체 {obj}의 해시값은 {hash_obj}이다") + print(f"노드 객체 {obj} → 해시값: {hash_obj}") diff --git a/ko/codes/python/chapter_stack_and_queue/array_deque.py b/ko/codes/python/chapter_stack_and_queue/array_deque.py index a838a1c96..cdd11bd48 100644 --- a/ko/codes/python/chapter_stack_and_queue/array_deque.py +++ b/ko/codes/python/chapter_stack_and_queue/array_deque.py @@ -108,13 +108,13 @@ if __name__ == "__main__": peek_last: int = deque.peek_last() print("맨 뒤 원소 peek_last =", peek_last) - # 큐에 원소 삽입 + # 원소 삽입 deque.push_last(4) print("원소 4를 맨 뒤에 삽입한 후 deque =", deque.to_array()) deque.push_first(1) print("원소 1을 맨 앞에 삽입한 후 deque =", deque.to_array()) - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop_last: int = deque.pop_last() print("맨 뒤에서 꺼낸 원소 =", pop_last, ", 맨 뒤에서 꺼낸 후 deque =", deque.to_array()) pop_first: int = deque.pop_first() diff --git a/ko/codes/python/chapter_stack_and_queue/array_queue.py b/ko/codes/python/chapter_stack_and_queue/array_queue.py index 915498265..31416de25 100644 --- a/ko/codes/python/chapter_stack_and_queue/array_queue.py +++ b/ko/codes/python/chapter_stack_and_queue/array_queue.py @@ -27,7 +27,7 @@ class ArrayQueue: return self._size == 0 def push(self, num: int): - """큐에 삽입""" + """원소 삽입""" if self._size == self.capacity(): raise IndexError("큐가 가득 찼다") # 맨 뒤 인덱스 + 1을 가리키는 맨 뒤 포인터를 계산한다 @@ -38,7 +38,7 @@ class ArrayQueue: self._size += 1 def pop(self) -> int: - """큐에서 꺼내기""" + """원소 꺼내기""" num: int = self.peek() # 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 self._front = (self._front + 1) % self.capacity() @@ -66,7 +66,7 @@ if __name__ == "__main__": # 큐 초기화 queue = ArrayQueue(10) - # 큐에 원소 삽입 + # 원소 삽입 queue.push(1) queue.push(3) queue.push(2) @@ -78,7 +78,7 @@ if __name__ == "__main__": peek: int = queue.peek() print("맨 앞 원소 peek =", peek) - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop: int = queue.pop() print("큐에서 꺼낸 원소 pop =", pop) print("큐에서 꺼낸 후 queue =", queue.to_list()) @@ -95,4 +95,4 @@ if __name__ == "__main__": for i in range(10): queue.push(i) queue.pop() - print("반복", i, "회에서 삽입 + 꺼내기를 수행한 후 queue = ", queue.to_list()) + print("반복", i, "회차에서 삽입 + 꺼내기를 수행한 후 queue = ", queue.to_list()) diff --git a/ko/codes/python/chapter_stack_and_queue/deque.py b/ko/codes/python/chapter_stack_and_queue/deque.py index 6552692e0..c3cc4aa5f 100644 --- a/ko/codes/python/chapter_stack_and_queue/deque.py +++ b/ko/codes/python/chapter_stack_and_queue/deque.py @@ -11,7 +11,7 @@ if __name__ == "__main__": # 덱 초기화 deq: deque[int] = deque() - # 큐에 원소 삽입 + # 원소 삽입 deq.append(2) # 맨 뒤에 추가한다 deq.append(5) deq.append(4) @@ -25,7 +25,7 @@ if __name__ == "__main__": rear: int = deq[-1] # 맨 뒤 원소 print("맨 뒤 원소 rear =", rear) - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop_front: int = deq.popleft() # 맨 앞 원소를 꺼낸다 print("맨 앞에서 꺼낸 원소 pop_front =", pop_front) print("맨 앞에서 꺼낸 후 deque =", deq) diff --git a/ko/codes/python/chapter_stack_and_queue/linkedlist_deque.py b/ko/codes/python/chapter_stack_and_queue/linkedlist_deque.py index 90dd3425c..ccf23acc6 100644 --- a/ko/codes/python/chapter_stack_and_queue/linkedlist_deque.py +++ b/ko/codes/python/chapter_stack_and_queue/linkedlist_deque.py @@ -33,7 +33,7 @@ class LinkedListDeque: return self._size == 0 def push(self, num: int, is_front: bool): - """큐 삽입 연산""" + """원소 삽입 연산""" node = ListNode(num) # 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다 if self.is_empty(): @@ -61,7 +61,7 @@ class LinkedListDeque: self.push(num, False) def pop(self, is_front: bool) -> int: - """큐에서 꺼내는 연산""" + """원소를 꺼내는 연산""" if self.is_empty(): raise IndexError("덱이 비어 있다") # 큐의 길이가 1이면 머리와 꼬리가 같은 노드를 가리킨다 @@ -133,13 +133,13 @@ if __name__ == "__main__": peek_last: int = deque.peek_last() print("맨 뒤 원소 peek_last =", peek_last) - # 큐에 원소 삽입 + # 원소 삽입 deque.push_last(4) print("원소 4를 맨 뒤에 삽입한 후 deque =", deque.to_array()) deque.push_first(1) print("원소 1을 맨 앞에 삽입한 후 deque =", deque.to_array()) - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop_last: int = deque.pop_last() print("맨 뒤에서 꺼낸 원소 =", pop_last, ", 맨 뒤에서 꺼낸 후 deque =", deque.to_array()) pop_first: int = deque.pop_first() diff --git a/ko/codes/python/chapter_stack_and_queue/linkedlist_queue.py b/ko/codes/python/chapter_stack_and_queue/linkedlist_queue.py index c654f7b84..6ff7c27f8 100644 --- a/ko/codes/python/chapter_stack_and_queue/linkedlist_queue.py +++ b/ko/codes/python/chapter_stack_and_queue/linkedlist_queue.py @@ -29,7 +29,7 @@ class LinkedListQueue: return self._size == 0 def push(self, num: int): - """큐에 삽입""" + """원소 삽입""" # 꼬리 노드 뒤에 num을 추가한다 node = ListNode(num) # 큐가 비어 있으면 머리와 꼬리 노드가 모두 해당 노드를 가리키게 한다 @@ -43,7 +43,7 @@ class LinkedListQueue: self._size += 1 def pop(self) -> int: - """큐에서 꺼내기""" + """원소 꺼내기""" num = self.peek() # 머리 노드를 삭제한다 self._front = self._front.next @@ -71,7 +71,7 @@ if __name__ == "__main__": # 큐 초기화 queue = LinkedListQueue() - # 큐에 원소 삽입 + # 원소 삽입 queue.push(1) queue.push(3) queue.push(2) @@ -83,7 +83,7 @@ if __name__ == "__main__": peek: int = queue.peek() print("맨 앞 원소 front =", peek) - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop_front: int = queue.pop() print("큐에서 꺼낸 원소 pop =", pop_front) print("큐에서 꺼낸 후 queue =", queue.to_list()) diff --git a/ko/codes/python/chapter_stack_and_queue/queue.py b/ko/codes/python/chapter_stack_and_queue/queue.py index 9406208bd..8c3a59184 100644 --- a/ko/codes/python/chapter_stack_and_queue/queue.py +++ b/ko/codes/python/chapter_stack_and_queue/queue.py @@ -13,7 +13,7 @@ if __name__ == "__main__": # queue.Queue()는 전용 큐 클래스이지만 사용하기가 그다지 편리하지 않다 que: deque[int] = deque() - # 큐에 원소 삽입 + # 원소 삽입 que.append(1) que.append(3) que.append(2) @@ -25,7 +25,7 @@ if __name__ == "__main__": front: int = que[0] print("맨 앞 원소 front =", front) - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop: int = que.popleft() print("큐에서 꺼낸 원소 pop =", pop) print("큐에서 꺼낸 후 que =", que) diff --git a/ko/codes/pythontutor/chapter_stack_and_queue/array_queue.md b/ko/codes/pythontutor/chapter_stack_and_queue/array_queue.md index 780b1f4e7..cd96441bd 100644 --- a/ko/codes/pythontutor/chapter_stack_and_queue/array_queue.md +++ b/ko/codes/pythontutor/chapter_stack_and_queue/array_queue.md @@ -5,4 +5,4 @@ ---> -https://pythontutor.com/render.html#code=class%20ArrayQueue%3A%0A%20%22%22%22%EC%9B%90%ED%98%95%20%EB%B0%B0%EC%97%B4%EB%A1%9C%20%EA%B5%AC%ED%98%84%ED%95%9C%20%ED%81%90%22%22%22%0A%0A%20def%20__init__%28self,%20size%3A%20int%29%3A%0A%20%20%22%22%22%EC%83%9D%EC%84%B1%EC%9E%90%22%22%22%0A%20%20self._nums%3A%20list%5Bint%5D%20%3D%20%5B0%5D%20%2A%20size%20%20%23%20%ED%81%90%EC%9D%98%20%EC%9B%90%EC%86%8C%EB%A5%BC%20%EC%A0%80%EC%9E%A5%ED%95%98%EB%8A%94%20%EB%B0%B0%EC%97%B4%0A%20%20self._front%3A%20int%20%3D%200%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%EB%A5%BC%20%EA%B0%80%EB%A6%AC%ED%82%A4%EB%8A%94%20%EB%A7%A8%20%EC%95%9E%20%ED%8F%AC%EC%9D%B8%ED%84%B0%0A%20%20self._size%3A%20int%20%3D%200%20%20%23%20%ED%81%90%20%EA%B8%B8%EC%9D%B4%0A%0A%20def%20capacity%28self%29%20-%3E%20int%3A%0A%20%20%22%22%22%ED%81%90%EC%9D%98%20%EC%9A%A9%EB%9F%89%20%EB%B0%98%ED%99%98%22%22%22%0A%20%20return%20len%28self._nums%29%0A%0A%20def%20size%28self%29%20-%3E%20int%3A%0A%20%20%22%22%22%ED%81%90%EC%9D%98%20%EA%B8%B8%EC%9D%B4%20%EB%B0%98%ED%99%98%22%22%22%0A%20%20return%20self._size%0A%0A%20def%20is_empty%28self%29%20-%3E%20bool%3A%0A%20%20%22%22%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%8C%90%EB%8B%A8%22%22%22%0A%20%20return%20self._size%20%3D%3D%200%0A%0A%20def%20push%28self,%20num%3A%20int%29%3A%0A%20%20%22%22%22%ED%81%90%EC%97%90%20%EC%82%BD%EC%9E%85%22%22%22%0A%20%20if%20self._size%20%3D%3D%20self.capacity%28%29%3A%0A%20%20%20raise%20IndexError%28%22%ED%81%90%EA%B0%80%20%EA%B0%80%EB%93%9D%20%EC%B0%BC%EB%8B%A4%22%29%0A%20%20%23%20%EB%A7%A8%20%EB%92%A4%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%20%2B%201%EC%9D%84%20%EA%B0%80%EB%A6%AC%ED%82%A4%EB%8A%94%20%EB%A7%A8%20%EB%92%A4%20%ED%8F%AC%EC%9D%B8%ED%84%B0%EB%A5%BC%20%EA%B3%84%EC%82%B0%ED%95%9C%EB%8B%A4%0A%20%20%23%20%EB%82%98%EB%A8%B8%EC%A7%80%20%EC%97%B0%EC%82%B0%EC%9D%84%20%ED%86%B5%ED%95%B4%20rear%EA%B0%80%20%EB%B0%B0%EC%97%B4%EC%9D%98%20%EB%81%9D%EC%9D%84%20%EB%84%98%EC%96%B4%EA%B0%80%EB%A9%B4%20%EC%B2%98%EC%9D%8C%EC%9C%BC%EB%A1%9C%20%EB%8F%8C%EC%95%84%EC%98%A4%EA%B2%8C%20%ED%95%9C%EB%8B%A4%0A%20%20rear%3A%20int%20%3D%20%28self._front%20%2B%20self._size%29%20%25%20self.capacity%28%29%0A%20%20%23%20num%EC%9D%84%20%EB%A7%A8%20%EB%92%A4%EC%97%90%20%EC%B6%94%EA%B0%80%ED%95%9C%EB%8B%A4%0A%20%20self._nums%5Brear%5D%20%3D%20num%0A%20%20self._size%20%2B%3D%201%0A%0A%20def%20pop%28self%29%20-%3E%20int%3A%0A%20%20%22%22%22%ED%81%90%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%22%22%22%0A%20%20num%3A%20int%20%3D%20self.peek%28%29%0A%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%ED%8F%AC%EC%9D%B8%ED%84%B0%EB%A5%BC%20%EB%92%A4%EB%A1%9C%20%ED%95%9C%20%EC%B9%B8%20%EC%9D%B4%EB%8F%99%ED%95%98%EA%B3%A0,%20%EB%81%9D%EC%9D%84%20%EB%84%98%EC%96%B4%EA%B0%80%EB%A9%B4%20%EB%B0%B0%EC%97%B4%EC%9D%98%20%EC%B2%98%EC%9D%8C%EC%9C%BC%EB%A1%9C%20%EB%8F%8C%EC%95%84%EC%98%A8%EB%8B%A4%0A%20%20self._front%20%3D%20%28self._front%20%2B%201%29%20%25%20self.capacity%28%29%0A%20%20self._size%20-%3D%201%0A%20%20return%20num%0A%0A%20def%20peek%28self%29%20-%3E%20int%3A%0A%20%20%22%22%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%22%22%22%0A%20%20if%20self.is_empty%28%29%3A%0A%20%20%20raise%20IndexError%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8B%A4%22%29%0A%20%20return%20self._nums%5Bself._front%5D%0A%0A%20def%20to_list%28self%29%20-%3E%20list%5Bint%5D%3A%0A%20%20%22%22%22%EC%B6%9C%EB%A0%A5%EC%97%90%20%EC%82%AC%EC%9A%A9%ED%95%A0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%B0%98%ED%99%98%22%22%22%0A%20%20res%20%3D%20%5B0%5D%20%2A%20self.size%28%29%0A%20%20j%3A%20int%20%3D%20self._front%0A%20%20for%20i%20in%20range%28self.size%28%29%29%3A%0A%20%20%20res%5Bi%5D%20%3D%20self._nums%5B%28j%20%25%20self.capacity%28%29%29%5D%0A%20%20%20j%20%2B%3D%201%0A%20%20return%20res%0A%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%23%20%ED%81%90%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20queue%20%3D%20ArrayQueue%2810%29%0A%0A%20%23%20%ED%81%90%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20queue.push%281%29%0A%20queue.push%283%29%0A%20queue.push%282%29%0A%20queue.push%285%29%0A%20queue.push%284%29%0A%0A%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20peek%20%3D%20queue.peek%28%29%0A%20print%28%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20peek%20%3D%22,%20peek%29%0A%0A%20%23%20%ED%81%90%EC%97%90%EC%84%9C%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20pop%20%3D%20queue.pop%28%29%0A%20print%28%22%ED%81%90%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20pop%20%3D%22,%20pop%29%0A%0A%20%23%20%ED%81%90%EC%9D%98%20%EA%B8%B8%EC%9D%B4%20%EB%B0%98%ED%99%98%0A%20size%20%3D%20queue.size%28%29%0A%20print%28%22%ED%81%90%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22,%20size%29%0A%0A%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%8C%90%EB%8B%A8%0A%20is_empty%20%3D%20queue.is_empty%28%29%0A%20print%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22,%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20ArrayQueue%3A%0A%20%20%22%22%22%EC%9B%90%ED%98%95%20%EB%B0%B0%EC%97%B4%EB%A1%9C%20%EA%B5%AC%ED%98%84%ED%95%9C%20%ED%81%90%22%22%22%0A%0A%20%20def%20__init__%28self,%20size%3A%20int%29%3A%0A%20%20%20%20%22%22%22%EC%83%9D%EC%84%B1%EC%9E%90%22%22%22%0A%20%20%20%20self._nums%3A%20list%5Bint%5D%20%3D%20%5B0%5D%20%2A%20size%20%20%23%20%ED%81%90%EC%9D%98%20%EC%9B%90%EC%86%8C%EB%A5%BC%20%EC%A0%80%EC%9E%A5%ED%95%98%EB%8A%94%20%EB%B0%B0%EC%97%B4%0A%20%20%20%20self._front%3A%20int%20%3D%200%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%EB%A5%BC%20%EA%B0%80%EB%A6%AC%ED%82%A4%EB%8A%94%20%EB%A7%A8%20%EC%95%9E%20%ED%8F%AC%EC%9D%B8%ED%84%B0%0A%20%20%20%20self._size%3A%20int%20%3D%200%20%20%23%20%ED%81%90%20%EA%B8%B8%EC%9D%B4%0A%0A%20%20def%20capacity%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%ED%81%90%EC%9D%98%20%EC%9A%A9%EB%9F%89%20%EB%B0%98%ED%99%98%22%22%22%0A%20%20%20%20return%20len%28self._nums%29%0A%0A%20%20def%20size%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%ED%81%90%EC%9D%98%20%EA%B8%B8%EC%9D%B4%20%EB%B0%98%ED%99%98%22%22%22%0A%20%20%20%20return%20self._size%0A%0A%20%20def%20is_empty%28self%29%20-%3E%20bool%3A%0A%20%20%20%20%22%22%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%8C%90%EB%8B%A8%22%22%22%0A%20%20%20%20return%20self._size%20%3D%3D%200%0A%0A%20%20def%20push%28self,%20num%3A%20int%29%3A%0A%20%20%20%20%22%22%22%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%22%22%22%0A%20%20%20%20if%20self._size%20%3D%3D%20self.capacity%28%29%3A%0A%20%20%20%20%20%20raise%20IndexError%28%22%ED%81%90%EA%B0%80%20%EA%B0%80%EB%93%9D%20%EC%B0%BC%EB%8B%A4%22%29%0A%20%20%20%20%23%20%EB%A7%A8%20%EB%92%A4%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%20%2B%201%EC%9D%84%20%EA%B0%80%EB%A6%AC%ED%82%A4%EB%8A%94%20%EB%A7%A8%20%EB%92%A4%20%ED%8F%AC%EC%9D%B8%ED%84%B0%EB%A5%BC%20%EA%B3%84%EC%82%B0%ED%95%9C%EB%8B%A4%0A%20%20%20%20%23%20%EB%82%98%EB%A8%B8%EC%A7%80%20%EC%97%B0%EC%82%B0%EC%9D%84%20%ED%86%B5%ED%95%B4%20rear%EA%B0%80%20%EB%B0%B0%EC%97%B4%EC%9D%98%20%EB%81%9D%EC%9D%84%20%EB%84%98%EC%96%B4%EA%B0%80%EB%A9%B4%20%EC%B2%98%EC%9D%8C%EC%9C%BC%EB%A1%9C%20%EB%8F%8C%EC%95%84%EC%98%A4%EA%B2%8C%20%ED%95%9C%EB%8B%A4%0A%20%20%20%20rear%3A%20int%20%3D%20%28self._front%20%2B%20self._size%29%20%25%20self.capacity%28%29%0A%20%20%20%20%23%20num%EC%9D%84%20%EB%A7%A8%20%EB%92%A4%EC%97%90%20%EC%B6%94%EA%B0%80%ED%95%9C%EB%8B%A4%0A%20%20%20%20self._nums%5Brear%5D%20%3D%20num%0A%20%20%20%20self._size%20%2B%3D%201%0A%0A%20%20def%20pop%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%22%22%22%0A%20%20%20%20num%3A%20int%20%3D%20self.peek%28%29%0A%20%20%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%ED%8F%AC%EC%9D%B8%ED%84%B0%EB%A5%BC%20%EB%92%A4%EB%A1%9C%20%ED%95%9C%20%EC%B9%B8%20%EC%9D%B4%EB%8F%99%ED%95%98%EA%B3%A0,%20%EB%81%9D%EC%9D%84%20%EB%84%98%EC%96%B4%EA%B0%80%EB%A9%B4%20%EB%B0%B0%EC%97%B4%EC%9D%98%20%EC%B2%98%EC%9D%8C%EC%9C%BC%EB%A1%9C%20%EB%8F%8C%EC%95%84%EC%98%A8%EB%8B%A4%0A%20%20%20%20self._front%20%3D%20%28self._front%20%2B%201%29%20%25%20self.capacity%28%29%0A%20%20%20%20self._size%20-%3D%201%0A%20%20%20%20return%20num%0A%0A%20%20def%20peek%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%22%22%22%0A%20%20%20%20if%20self.is_empty%28%29%3A%0A%20%20%20%20%20%20raise%20IndexError%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8B%A4%22%29%0A%20%20%20%20return%20self._nums%5Bself._front%5D%0A%0A%20%20def%20to_list%28self%29%20-%3E%20list%5Bint%5D%3A%0A%20%20%20%20%22%22%22%EC%B6%9C%EB%A0%A5%EC%97%90%20%EC%82%AC%EC%9A%A9%ED%95%A0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%B0%98%ED%99%98%22%22%22%0A%20%20%20%20res%20%3D%20%5B0%5D%20%2A%20self.size%28%29%0A%20%20%20%20j%3A%20int%20%3D%20self._front%0A%20%20%20%20for%20i%20in%20range%28self.size%28%29%29%3A%0A%20%20%20%20%20%20res%5Bi%5D%20%3D%20self._nums%5B%28j%20%25%20self.capacity%28%29%29%5D%0A%20%20%20%20%20%20j%20%2B%3D%201%0A%20%20%20%20return%20res%0A%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%23%20%ED%81%90%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20queue%20%3D%20ArrayQueue%2810%29%0A%0A%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20queue.push%281%29%0A%20%20queue.push%283%29%0A%20%20queue.push%282%29%0A%20%20queue.push%285%29%0A%20%20queue.push%284%29%0A%0A%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20%20peek%20%3D%20queue.peek%28%29%0A%20%20print%28%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20peek%20%3D%22,%20peek%29%0A%0A%20%20%23%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20pop%20%3D%20queue.pop%28%29%0A%20%20print%28%22%ED%81%90%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20pop%20%3D%22,%20pop%29%0A%0A%20%20%23%20%ED%81%90%EC%9D%98%20%EA%B8%B8%EC%9D%B4%20%EB%B0%98%ED%99%98%0A%20%20size%20%3D%20queue.size%28%29%0A%20%20print%28%22%ED%81%90%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22,%20size%29%0A%0A%20%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%8C%90%EB%8B%A8%0A%20%20is_empty%20%3D%20queue.is_empty%28%29%0A%20%20print%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22,%20is_empty%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/pythontutor/chapter_stack_and_queue/linkedlist_queue.md b/ko/codes/pythontutor/chapter_stack_and_queue/linkedlist_queue.md index ce3b74b4f..03a168d30 100644 --- a/ko/codes/pythontutor/chapter_stack_and_queue/linkedlist_queue.md +++ b/ko/codes/pythontutor/chapter_stack_and_queue/linkedlist_queue.md @@ -5,4 +5,4 @@ ---> -https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%EB%8B%A4%EC%9D%8C%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%0Aclass%20LinkedListQueue%3A%0A%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A1%9C%20%EA%B5%AC%ED%98%84%ED%95%9C%20%ED%81%90%22%22%22%0A%0A%20%20def%20__init__%28self%29%3A%0A%20%20%20%20%22%22%22%EC%83%9D%EC%84%B1%EC%9E%90%22%22%22%0A%20%20%20%20self._front%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%EB%A8%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%20front%0A%20%20%20%20self._rear%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%EA%BC%AC%EB%A6%AC%20%EB%85%B8%EB%93%9C%20rear%0A%20%20%20%20self._size%3A%20int%20%3D%200%0A%0A%20%20def%20size%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%ED%81%90%EC%9D%98%20%EA%B8%B8%EC%9D%B4%20%EB%B0%98%ED%99%98%22%22%22%0A%20%20%20%20return%20self._size%0A%0A%20%20def%20is_empty%28self%29%20-%3E%20bool%3A%0A%20%20%20%20%22%22%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%8C%90%EB%8B%A8%22%22%22%0A%20%20%20%20return%20not%20self._front%0A%0A%20%20def%20push%28self,%20num%3A%20int%29%3A%0A%20%20%20%20%22%22%22%ED%81%90%EC%97%90%20%EC%82%BD%EC%9E%85%22%22%22%0A%20%20%20%20%23%20%EA%BC%AC%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%EB%92%A4%EC%97%90%20num%EC%9D%84%20%EC%B6%94%EA%B0%80%ED%95%9C%EB%8B%A4%0A%20%20%20%20node%20%3D%20ListNode%28num%29%0A%20%20%20%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EC%9C%BC%EB%A9%B4%20%EB%A8%B8%EB%A6%AC%EC%99%80%20%EA%BC%AC%EB%A6%AC%20%EB%85%B8%EB%93%9C%EA%B0%80%20%EB%AA%A8%EB%91%90%20%ED%95%B4%EB%8B%B9%20%EB%85%B8%EB%93%9C%EB%A5%BC%20%EA%B0%80%EB%A6%AC%ED%82%A4%EA%B2%8C%20%ED%95%9C%EB%8B%A4%0A%20%20%20%20if%20self._front%20is%20None%3A%0A%20%20%20%20%20%20self._front%20%3D%20node%0A%20%20%20%20%20%20self._rear%20%3D%20node%0A%20%20%20%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EC%A7%80%20%EC%95%8A%EC%9C%BC%EB%A9%B4%20%ED%95%B4%EB%8B%B9%20%EB%85%B8%EB%93%9C%EB%A5%BC%20%EA%BC%AC%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%EB%92%A4%EC%97%90%20%EC%B6%94%EA%B0%80%ED%95%9C%EB%8B%A4%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20self._rear.next%20%3D%20node%0A%20%20%20%20%20%20self._rear%20%3D%20node%0A%20%20%20%20self._size%20%2B%3D%201%0A%0A%20%20def%20pop%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%ED%81%90%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%22%22%22%0A%20%20%20%20num%20%3D%20self.peek%28%29%0A%20%20%20%20%23%20%EB%A8%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%EB%A5%BC%20%EC%82%AD%EC%A0%9C%ED%95%9C%EB%8B%A4%0A%20%20%20%20self._front%20%3D%20self._front.next%0A%20%20%20%20self._size%20-%3D%201%0A%20%20%20%20return%20num%0A%0A%20%20def%20peek%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%22%22%22%0A%20%20%20%20if%20self.is_empty%28%29%3A%0A%20%20%20%20%20%20raise%20IndexError%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8B%A4%22%29%0A%20%20%20%20return%20self._front.val%0A%0A%20%20def%20to_list%28self%29%20-%3E%20list%5Bint%5D%3A%0A%20%20%20%20%22%22%22%EC%B6%9C%EB%A0%A5%EC%97%90%20%EC%82%AC%EC%9A%A9%ED%95%A0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A1%9C%20%EB%B3%80%ED%99%98%22%22%22%0A%20%20%20%20queue%20%3D%20%5B%5D%0A%20%20%20%20temp%20%3D%20self._front%0A%20%20%20%20while%20temp%3A%0A%20%20%20%20%20%20queue.append%28temp.val%29%0A%20%20%20%20%20%20temp%20%3D%20temp.next%0A%20%20%20%20return%20queue%0A%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%23%20%ED%81%90%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20queue%20%3D%20LinkedListQueue%28%29%0A%0A%20%20%23%20%ED%81%90%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20queue.push%281%29%0A%20%20queue.push%283%29%0A%20%20queue.push%282%29%0A%20%20queue.push%285%29%0A%20%20queue.push%284%29%0A%20%20print%28%22%ED%81%90%20queue%20%3D%22,%20queue.to_list%28%29%29%0A%0A%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20%20peek%20%3D%20queue.peek%28%29%0A%20%20print%28%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20front%20%3D%22,%20peek%29%0A%0A%20%20%23%20%ED%81%90%EC%97%90%EC%84%9C%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20pop_front%20%3D%20queue.pop%28%29%0A%20%20print%28%22%ED%81%90%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20pop%20%3D%22,%20pop_front%29%0A%20%20print%28%22%ED%81%90%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%ED%9B%84%20queue%20%3D%22,%20queue.to_list%28%29%29%0A%0A%20%20%23%20%ED%81%90%EC%9D%98%20%EA%B8%B8%EC%9D%B4%20%EB%B0%98%ED%99%98%0A%20%20size%20%3D%20queue.size%28%29%0A%20%20print%28%22%ED%81%90%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22,%20size%29%0A%0A%20%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%8C%90%EB%8B%A8%0A%20%20is_empty%20%3D%20queue.is_empty%28%29%0A%20%20print%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22,%20is_empty%29&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%EB%8B%A4%EC%9D%8C%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%0Aclass%20LinkedListQueue%3A%0A%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A1%9C%20%EA%B5%AC%ED%98%84%ED%95%9C%20%ED%81%90%22%22%22%0A%0A%20%20def%20__init__%28self%29%3A%0A%20%20%20%20%22%22%22%EC%83%9D%EC%84%B1%EC%9E%90%22%22%22%0A%20%20%20%20self._front%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%EB%A8%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%20front%0A%20%20%20%20self._rear%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%EA%BC%AC%EB%A6%AC%20%EB%85%B8%EB%93%9C%20rear%0A%20%20%20%20self._size%3A%20int%20%3D%200%0A%0A%20%20def%20size%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%ED%81%90%EC%9D%98%20%EA%B8%B8%EC%9D%B4%20%EB%B0%98%ED%99%98%22%22%22%0A%20%20%20%20return%20self._size%0A%0A%20%20def%20is_empty%28self%29%20-%3E%20bool%3A%0A%20%20%20%20%22%22%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%8C%90%EB%8B%A8%22%22%22%0A%20%20%20%20return%20not%20self._front%0A%0A%20%20def%20push%28self,%20num%3A%20int%29%3A%0A%20%20%20%20%22%22%22%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%22%22%22%0A%20%20%20%20%23%20%EA%BC%AC%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%EB%92%A4%EC%97%90%20num%EC%9D%84%20%EC%B6%94%EA%B0%80%ED%95%9C%EB%8B%A4%0A%20%20%20%20node%20%3D%20ListNode%28num%29%0A%20%20%20%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EC%9C%BC%EB%A9%B4%20%EB%A8%B8%EB%A6%AC%EC%99%80%20%EA%BC%AC%EB%A6%AC%20%EB%85%B8%EB%93%9C%EA%B0%80%20%EB%AA%A8%EB%91%90%20%ED%95%B4%EB%8B%B9%20%EB%85%B8%EB%93%9C%EB%A5%BC%20%EA%B0%80%EB%A6%AC%ED%82%A4%EA%B2%8C%20%ED%95%9C%EB%8B%A4%0A%20%20%20%20if%20self._front%20is%20None%3A%0A%20%20%20%20%20%20self._front%20%3D%20node%0A%20%20%20%20%20%20self._rear%20%3D%20node%0A%20%20%20%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EC%A7%80%20%EC%95%8A%EC%9C%BC%EB%A9%B4%20%ED%95%B4%EB%8B%B9%20%EB%85%B8%EB%93%9C%EB%A5%BC%20%EA%BC%AC%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%EB%92%A4%EC%97%90%20%EC%B6%94%EA%B0%80%ED%95%9C%EB%8B%A4%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20self._rear.next%20%3D%20node%0A%20%20%20%20%20%20self._rear%20%3D%20node%0A%20%20%20%20self._size%20%2B%3D%201%0A%0A%20%20def%20pop%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%22%22%22%0A%20%20%20%20num%20%3D%20self.peek%28%29%0A%20%20%20%20%23%20%EB%A8%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%EB%A5%BC%20%EC%82%AD%EC%A0%9C%ED%95%9C%EB%8B%A4%0A%20%20%20%20self._front%20%3D%20self._front.next%0A%20%20%20%20self._size%20-%3D%201%0A%20%20%20%20return%20num%0A%0A%20%20def%20peek%28self%29%20-%3E%20int%3A%0A%20%20%20%20%22%22%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%22%22%22%0A%20%20%20%20if%20self.is_empty%28%29%3A%0A%20%20%20%20%20%20raise%20IndexError%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8B%A4%22%29%0A%20%20%20%20return%20self._front.val%0A%0A%20%20def%20to_list%28self%29%20-%3E%20list%5Bint%5D%3A%0A%20%20%20%20%22%22%22%EC%B6%9C%EB%A0%A5%EC%97%90%20%EC%82%AC%EC%9A%A9%ED%95%A0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A1%9C%20%EB%B3%80%ED%99%98%22%22%22%0A%20%20%20%20queue%20%3D%20%5B%5D%0A%20%20%20%20temp%20%3D%20self._front%0A%20%20%20%20while%20temp%3A%0A%20%20%20%20%20%20queue.append%28temp.val%29%0A%20%20%20%20%20%20temp%20%3D%20temp.next%0A%20%20%20%20return%20queue%0A%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%23%20%ED%81%90%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20queue%20%3D%20LinkedListQueue%28%29%0A%0A%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20queue.push%281%29%0A%20%20queue.push%283%29%0A%20%20queue.push%282%29%0A%20%20queue.push%285%29%0A%20%20queue.push%284%29%0A%20%20print%28%22%ED%81%90%20queue%20%3D%22,%20queue.to_list%28%29%29%0A%0A%20%20%23%20%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20%20peek%20%3D%20queue.peek%28%29%0A%20%20print%28%22%EB%A7%A8%20%EC%95%9E%20%EC%9B%90%EC%86%8C%20front%20%3D%22,%20peek%29%0A%0A%20%20%23%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20pop_front%20%3D%20queue.pop%28%29%0A%20%20print%28%22%ED%81%90%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%20pop%20%3D%22,%20pop_front%29%0A%20%20print%28%22%ED%81%90%EC%97%90%EC%84%9C%20%EA%BA%BC%EB%82%B8%20%ED%9B%84%20queue%20%3D%22,%20queue.to_list%28%29%29%0A%0A%20%20%23%20%ED%81%90%EC%9D%98%20%EA%B8%B8%EC%9D%B4%20%EB%B0%98%ED%99%98%0A%20%20size%20%3D%20queue.size%28%29%0A%20%20print%28%22%ED%81%90%20%EA%B8%B8%EC%9D%B4%20size%20%3D%22,%20size%29%0A%0A%20%20%23%20%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%8C%90%EB%8B%A8%0A%20%20is_empty%20%3D%20queue.is_empty%28%29%0A%20%20print%28%22%ED%81%90%EA%B0%80%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EA%B0%80%20%3D%22,%20is_empty%29&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/ruby/chapter_hashing/built_in_hash.rb b/ko/codes/ruby/chapter_hashing/built_in_hash.rb index 183adc3cf..659962d1b 100644 --- a/ko/codes/ruby/chapter_hashing/built_in_hash.rb +++ b/ko/codes/ruby/chapter_hashing/built_in_hash.rb @@ -10,25 +10,25 @@ require_relative '../utils/list_node' if __FILE__ == $0 num = 3 hash_num = num.hash - puts "정수 #{num}의 해시값: #{hash_num}" + puts "정수 #{num} → 해시값: #{hash_num}" bol = true hash_bol = bol.hash - puts "불리언 #{bol}의 해시값: #{hash_bol}" + puts "불리언 값 #{bol} → 해시값: #{hash_bol}" dec = 3.14159 hash_dec = dec.hash - puts "소수 #{dec}의 해시값: #{hash_dec}" + puts "소수 #{dec} → 해시값: #{hash_dec}" str = "Hello 算法" hash_str = str.hash puts "문자열 #{str}의 해시값: #{hash_str}" - tup = [12836, '小哈'] - hash_tup = tup.hash - puts "튜플 #{tup}의 해시값: #{hash_tup}" + arr = [12836, '小哈'] + hash_arr = arr.hash + puts "배열 #{arr} → 해시값: #{hash_arr}" obj = ListNode.new(0) hash_obj = obj.hash - puts "노드 객체 #{obj}의 해시값: #{hash_obj}" + puts "노드 객체 #{obj} → 해시값: #{hash_obj}" end diff --git a/ko/codes/ruby/chapter_stack_and_queue/array_deque.rb b/ko/codes/ruby/chapter_stack_and_queue/array_deque.rb index a48a8f927..7118e1159 100644 --- a/ko/codes/ruby/chapter_stack_and_queue/array_deque.rb +++ b/ko/codes/ruby/chapter_stack_and_queue/array_deque.rb @@ -123,17 +123,17 @@ if __FILE__ == $0 peek_last = deque.peek_last puts "맨 뒤 원소 peek_last = #{peek_last}" - # 큐에 원소 삽입 + # 원소 삽입 deque.push_last(4) puts "뒤쪽에 원소 4를 삽입한 후 deque = #{deque.to_array}" deque.push_first(1) - puts "뒤쪽에 원소 1을 삽입한 후 deque = #{deque.to_array}" + puts "앞쪽에 원소 1을 삽입한 후 deque = #{deque.to_array}" - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop_last = deque.pop_last puts "맨 뒤에서 꺼낸 원소 = #{pop_last}, 맨 뒤에서 꺼낸 후 deque = #{deque.to_array}" pop_first = deque.pop_first - puts "맨 뒤에서 꺼낸 원소 = #{pop_first}, 맨 뒤에서 꺼낸 후 deque = #{deque.to_array}" + puts "맨 앞에서 꺼낸 원소 = #{pop_first}, 맨 앞에서 꺼낸 후 deque = #{deque.to_array}" # 덱의 길이 반환 size = deque.size diff --git a/ko/codes/ruby/chapter_stack_and_queue/array_queue.rb b/ko/codes/ruby/chapter_stack_and_queue/array_queue.rb index 3c38355ba..45ad4063f 100644 --- a/ko/codes/ruby/chapter_stack_and_queue/array_queue.rb +++ b/ko/codes/ruby/chapter_stack_and_queue/array_queue.rb @@ -26,7 +26,7 @@ class ArrayQueue size.zero? end - ### 큐에 삽입 ### + ### 원소 삽입 ### def push(num) raise IndexError, '큐가 가득 찼다' if size == capacity @@ -38,7 +38,7 @@ class ArrayQueue @size += 1 end - ### 큐에서 꺼내기 ### + ### 원소 꺼내기 ### def pop num = peek # 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -73,7 +73,7 @@ if __FILE__ == $0 # 큐 초기화 queue = ArrayQueue.new(10) - # 큐에 원소 삽입 + # 원소 삽입 queue.push(1) queue.push(3) queue.push(2) @@ -85,7 +85,7 @@ if __FILE__ == $0 peek = queue.peek puts "맨 앞 원소 peek = #{peek}" - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop = queue.pop puts "큐에서 꺼낸 원소 pop = #{pop}" puts "큐에서 꺼낸 후 queue = #{queue.to_array}" @@ -102,6 +102,6 @@ if __FILE__ == $0 for i in 0...10 queue.push(i) queue.pop - puts "반복 #{i}회에서 삽입 + 꺼내기를 수행한 후 queue = #{queue.to_array}" + puts "반복 #{i} 회차에서 삽입 + 꺼내기를 수행한 후 queue = #{queue.to_array}" end end diff --git a/ko/codes/ruby/chapter_stack_and_queue/deque.rb b/ko/codes/ruby/chapter_stack_and_queue/deque.rb index 2bdd62381..0527f0dcf 100644 --- a/ko/codes/ruby/chapter_stack_and_queue/deque.rb +++ b/ko/codes/ruby/chapter_stack_and_queue/deque.rb @@ -7,10 +7,10 @@ Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) ### 실행 코드 ### if __FILE__ == $0 # 덱 초기화 - # Ruby에는 내장 덱이 없으므로 Array를 덱으로 사용한다 + # Ruby에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 deque = [] - # 큐에 원소 삽입 + # 원소 삽입 deque << 2 deque << 5 deque << 4 @@ -25,7 +25,7 @@ if __FILE__ == $0 peek_last = deque.last puts "맨 뒤 원소 peek_last = #{peek_last}" - # 큐에서 원소 꺼내기 + # 원소 꺼내기 # 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 유의한다 pop_front = deque.shift puts "맨 앞에서 꺼낸 원소 pop_front = #{pop_front}, 맨 앞에서 꺼낸 후 deque = #{deque}" diff --git a/ko/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb b/ko/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb index f47c11e31..26f329690 100644 --- a/ko/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/ko/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,7 +4,7 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end -### 이중 연결 리스트 노드 +### 이중 연결 리스트 노드 ### class ListNode attr_accessor :val attr_accessor :next # 다음 노드 참조 @@ -33,7 +33,7 @@ class LinkedListDeque size.zero? end - ### 큐 삽입 연산 ### + ### 원소 삽입 연산 ### def push(num, is_front) node = ListNode.new(num) # 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다 @@ -65,7 +65,7 @@ class LinkedListDeque push(num, false) end - ### 큐에서 꺼내는 연산 ### + ### 원소를 꺼내는 연산 ### def pop(is_front) raise IndexError, '덱이 비어 있다' if is_empty? @@ -101,7 +101,7 @@ class LinkedListDeque pop(true) end - ### 맨 앞에서 꺼내기 ### + ### 맨 뒤에서 꺼내기 ### def pop_last pop(false) end @@ -145,15 +145,15 @@ if __FILE__ == $0 peek_first = deque.peek_first puts "맨 앞 원소 peek_first = #{peek_first}" peek_last = deque.peek_last - puts "맨 앞 원소 peek_last = #{peek_last}" + puts "맨 뒤 원소 peek_last = #{peek_last}" - # 큐에 원소 삽입 + # 원소 삽입 deque.push_last(4) puts "뒤쪽에 원소 4를 삽입한 후 deque = #{deque.to_array}" deque.push_first(1) puts "앞쪽에 원소 1을 삽입한 후 deque = #{deque.to_array}" - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop_last = deque.pop_last puts "맨 뒤에서 꺼낸 원소 = #{pop_last}, 맨 뒤에서 꺼낸 후 deque = #{deque.to_array}" pop_first = deque.pop_first diff --git a/ko/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb b/ko/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb index 5751859df..faa89d8c1 100644 --- a/ko/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb +++ b/ko/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb @@ -23,7 +23,7 @@ class LinkedListQueue @front.nil? end - ### 큐에 삽입 ### + ### 원소 삽입 ### def push(num) # 꼬리 노드 뒤에 num을 추가한다 node = ListNode.new(num) @@ -41,7 +41,7 @@ class LinkedListQueue @size += 1 end - ### 큐에서 꺼내기 ### + ### 원소 꺼내기 ### def pop num = peek # 머리 노드를 삭제한다 @@ -74,7 +74,7 @@ if __FILE__ == $0 # 큐 초기화 queue = LinkedListQueue.new - # 큐에 원소 삽입 + # 원소 삽입 queue.push(1) queue.push(3) queue.push(2) @@ -86,7 +86,7 @@ if __FILE__ == $0 peek = queue.peek puts "맨 앞 원소 front = #{peek}" - # 큐에서 원소 꺼내기 + # 원소 꺼내기 pop_front = queue.pop puts "큐에서 꺼낸 원소 pop = #{pop_front}" puts "큐에서 꺼낸 후 queue = #{queue.to_array}" diff --git a/ko/codes/ruby/chapter_stack_and_queue/queue.rb b/ko/codes/ruby/chapter_stack_and_queue/queue.rb index 8224ee038..6c658a1ab 100644 --- a/ko/codes/ruby/chapter_stack_and_queue/queue.rb +++ b/ko/codes/ruby/chapter_stack_and_queue/queue.rb @@ -10,7 +10,7 @@ if __FILE__ == $0 # Ruby의 내장 큐(Thread::Queue)에는 peek 메서드와 순회 메서드가 없으므로 Array를 큐로 사용할 수 있다 queue = [] - # 큐에 원소 삽입 + # 원소 삽입 queue.push(1) queue.push(3) queue.push(2) @@ -22,7 +22,7 @@ if __FILE__ == $0 peek = queue.first puts "맨 앞 원소 peek = #{peek}" - # 큐에서 원소 꺼내기 + # 원소 꺼내기 # 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 유의한다 pop = queue.shift puts "큐에서 꺼낸 원소 pop = #{pop}" diff --git a/ko/codes/rust/chapter_hashing/build_in_hash.rs b/ko/codes/rust/chapter_hashing/build_in_hash.rs index 86a347a0b..904ad40e2 100644 --- a/ko/codes/rust/chapter_hashing/build_in_hash.rs +++ b/ko/codes/rust/chapter_hashing/build_in_hash.rs @@ -15,19 +15,19 @@ fn main() { let mut num_hasher = DefaultHasher::new(); num.hash(&mut num_hasher); let hash_num = num_hasher.finish(); - println!("정수 {}의 해시값: {}", num, hash_num); + println!("정수 {} → 해시값: {}", num, hash_num); let bol = true; let mut bol_hasher = DefaultHasher::new(); bol.hash(&mut bol_hasher); let hash_bol = bol_hasher.finish(); - println!("불리언 {}의 해시값: {}", bol, hash_bol); + println!("불리언 값 {} → 해시값: {}", bol, hash_bol); let dec: f32 = 3.14159; let mut dec_hasher = DefaultHasher::new(); dec.to_bits().hash(&mut dec_hasher); let hash_dec = dec_hasher.finish(); - println!("소수 {}의 해시값: {}", dec, hash_dec); + println!("소수 {} → 해시값: {}", dec, hash_dec); let str = "Hello 算法"; let mut str_hasher = DefaultHasher::new(); @@ -39,11 +39,11 @@ fn main() { let mut tup_hasher = DefaultHasher::new(); arr.hash(&mut tup_hasher); let hash_tup = tup_hasher.finish(); - println!("튜플 {:?}의 해시값: {}", arr, hash_tup); + println!("튜플 {:?} → 해시값: {}", arr, hash_tup); let node = ListNode::new(42); let mut hasher = DefaultHasher::new(); node.borrow().val.hash(&mut hasher); let hash = hasher.finish(); - println!("노드 객체 {:?}의 해시값: {}", node, hash); + println!("노드 객체 {:?} → 해시값: {}", node, hash); } diff --git a/ko/codes/rust/chapter_stack_and_queue/array_deque.rs b/ko/codes/rust/chapter_stack_and_queue/array_deque.rs index 74069cb8e..d95859e61 100644 --- a/ko/codes/rust/chapter_stack_and_queue/array_deque.rs +++ b/ko/codes/rust/chapter_stack_and_queue/array_deque.rs @@ -134,7 +134,7 @@ fn main() { let peek_last = deque.peek_last(); print!("\n맨 뒤 원소 peek_last = {}", peek_last); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.push_last(4); print!("\n원소 4를 뒤에 삽입한 뒤 deque = "); print_util::print_array(&deque.to_array()); @@ -142,7 +142,7 @@ fn main() { print!("\n원소 1을 앞에 삽입한 뒤 deque = "); print_util::print_array(&deque.to_array()); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ let pop_last = deque.pop_last(); print!("\n뒤에서 꺼낸 원소 = {}, 꺼낸 뒤 deque = ", pop_last); print_util::print_array(&deque.to_array()); diff --git a/ko/codes/rust/chapter_stack_and_queue/array_queue.rs b/ko/codes/rust/chapter_stack_and_queue/array_queue.rs index cf59eed29..c9fdb1234 100644 --- a/ko/codes/rust/chapter_stack_and_queue/array_queue.rs +++ b/ko/codes/rust/chapter_stack_and_queue/array_queue.rs @@ -38,7 +38,7 @@ impl ArrayQueue { self.que_size == 0 } - /* 큐에 삽입 */ + /* 원소 삽입 */ fn push(&mut self, num: T) { if self.que_size == self.capacity() { println!("큐가 가득 찼다"); @@ -52,7 +52,7 @@ impl ArrayQueue { self.que_size += 1; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ fn pop(&mut self) -> T { let num = self.peek(); // 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -88,7 +88,7 @@ fn main() { let capacity = 10; let mut queue = ArrayQueue::new(capacity); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -100,7 +100,7 @@ fn main() { let peek = queue.peek(); println!("맨 앞 원소 peek = {}", peek); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ let pop = queue.pop(); println!( "꺼낸 원소 pop = {:?}, 꺼낸 뒤 queue = {:?}", @@ -120,6 +120,6 @@ fn main() { for i in 0..10 { queue.push(i); queue.pop(); - println!("{:?}번째 삽입 + 꺼내기 후 queue = {:?}", i, queue.to_vector()); + println!("반복 {:?} 회차에서 삽입 + 꺼내기를 수행한 후 queue = {:?}", i, queue.to_vector()); } } diff --git a/ko/codes/rust/chapter_stack_and_queue/deque.rs b/ko/codes/rust/chapter_stack_and_queue/deque.rs index 950e7b656..dbe91acb1 100644 --- a/ko/codes/rust/chapter_stack_and_queue/deque.rs +++ b/ko/codes/rust/chapter_stack_and_queue/deque.rs @@ -23,7 +23,7 @@ pub fn main() { let peek_last = deque.back().unwrap(); print!("\n맨 뒤 원소 peekLast = {peek_last}"); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.push_back(4); print!("\n원소 4를 뒤에 삽입한 뒤 deque = "); print_util::print_queue(&deque); @@ -31,7 +31,7 @@ pub fn main() { print!("\n원소 1을 앞에 삽입한 뒤 deque = "); print_util::print_queue(&deque); - // 큐에서 원소 꺼내기 + // 원소 꺼내기 let pop_last = deque.pop_back().unwrap(); print!("\n뒤에서 꺼낸 원소 = {pop_last}, 꺼낸 뒤 deque = "); print_util::print_queue(&deque); diff --git a/ko/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs b/ko/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs index 1cdaf3fff..9f7598b8e 100644 --- a/ko/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs +++ b/ko/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs @@ -53,7 +53,7 @@ impl LinkedListDeque { return self.que_size == 0; } - /* 큐 삽입 연산 */ + /* 원소 삽입 연산 */ fn push(&mut self, num: T, is_front: bool) { let node = ListNode::new(num); // 맨 앞에 삽입하는 연산 @@ -101,7 +101,7 @@ impl LinkedListDeque { self.push(num, false); } - /* 큐에서 꺼내는 연산 */ + /* 원소를 꺼내는 연산 */ fn pop(&mut self, is_front: bool) -> Option { // 큐가 비어 있으면 바로 None을 반환한다 if self.is_empty() { @@ -192,7 +192,7 @@ fn main() { let peek_last = deque.peek_last().unwrap().borrow().val; print!("\n맨 뒤 원소 peek_last = {}", peek_last); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.push_last(4); print!("\n원소 4를 뒤에 삽입한 뒤 deque = "); print_util::print_array(&deque.to_array(deque.peek_first())); @@ -200,7 +200,7 @@ fn main() { print!("\n원소 1을 앞에 삽입한 뒤 deque = "); print_util::print_array(&deque.to_array(deque.peek_first())); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ let pop_last = deque.pop_last().unwrap(); print!("\n뒤에서 꺼낸 원소 = {}, 꺼낸 뒤 deque = ", pop_last); print_util::print_array(&deque.to_array(deque.peek_first())); diff --git a/ko/codes/rust/chapter_stack_and_queue/linkedlist_queue.rs b/ko/codes/rust/chapter_stack_and_queue/linkedlist_queue.rs index a8365a647..3729e6817 100644 --- a/ko/codes/rust/chapter_stack_and_queue/linkedlist_queue.rs +++ b/ko/codes/rust/chapter_stack_and_queue/linkedlist_queue.rs @@ -36,7 +36,7 @@ impl LinkedListQueue { return self.que_size == 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ pub fn push(&mut self, num: T) { // 꼬리 노드 뒤에 num을 추가한다 let new_rear = ListNode::new(num); @@ -55,7 +55,7 @@ impl LinkedListQueue { self.que_size += 1; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ pub fn pop(&mut self) -> Option { self.front.take().map(|old_front| { match old_front.borrow_mut().next.take() { @@ -98,7 +98,7 @@ fn main() { /* 큐 초기화 */ let mut queue = LinkedListQueue::new(); - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -111,7 +111,7 @@ fn main() { let peek = queue.peek().unwrap().borrow().val; print!("\n맨 앞 원소 peek = {}", peek); - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ let pop = queue.pop().unwrap(); print!("\n꺼낸 원소 pop = {}, 꺼낸 뒤 queue = ", pop); print_util::print_array(&queue.to_array(queue.peek())); diff --git a/ko/codes/rust/chapter_stack_and_queue/queue.rs b/ko/codes/rust/chapter_stack_and_queue/queue.rs index 37bbd89f7..fa7c2b7fa 100644 --- a/ko/codes/rust/chapter_stack_and_queue/queue.rs +++ b/ko/codes/rust/chapter_stack_and_queue/queue.rs @@ -13,7 +13,7 @@ pub fn main() { // 큐 초기화 let mut queue: VecDeque = VecDeque::new(); - // 큐에 원소 삽입 + // 원소 삽입 queue.push_back(1); queue.push_back(3); queue.push_back(2); @@ -26,7 +26,7 @@ pub fn main() { let peek = queue.front().unwrap(); println!("\n맨 앞 원소 peek = {peek}"); - // 큐에서 원소 꺼내기 + // 원소 꺼내기 let pop = queue.pop_front().unwrap(); print!("꺼낸 원소 pop = {pop}, 꺼낸 뒤 queue = "); print_util::print_queue(&queue); diff --git a/ko/codes/snippets/chapter_array_and_linkedlist/array.md b/ko/codes/snippets/chapter_array_and_linkedlist/array.md index 7ef9a8b6f..1c1ca8d41 100644 --- a/ko/codes/snippets/chapter_array_and_linkedlist/array.md +++ b/ko/codes/snippets/chapter_array_and_linkedlist/array.md @@ -7,12 +7,12 @@ nums: list[int] = [1, 3, 2, 5, 4] ```cpp title="array.cpp" /* 배열 초기화 */ -// 스택에 저장 +// 스택에 저장한다 int arr[5] = {}; -int nums[5] = { 1, 3, 2, 5, 4 }; -// 힙에 저장(공간을 직접 해제해야 함) -int* arr1 = new int[5] {}; -int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +int nums[5] = {1, 3, 2, 5, 4}; +// 힙에 저장한다(메모리 공간을 직접 해제해야 한다) +int *arr1 = new int[5]{}; +int *nums1 = new int[5]{1, 3, 2, 5, 4}; ``` ```java title="array.java" @@ -22,7 +22,7 @@ int[] nums = { 1, 3, 2, 5, 4 }; ``` ```csharp title="array.cs" -/* 배열 초기화 */ +// 배열 초기화 int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] int[] nums = [1, 3, 2, 5, 4]; ``` @@ -30,56 +30,55 @@ int[] nums = [1, 3, 2, 5, 4]; ```go title="array.go" /* 배열 초기화 */ var arr [5]int -// Go에서 길이를 지정하면([5]int) 배열이고, 지정하지 않으면([]int) 슬라이스다 -// Go 배열의 길이는 컴파일 시 결정되도록 설계되었으므로 상수로만 길이를 지정할 수 있다 -// 용량 확장 메서드 extend()를 쉽게 구현하기 위해 아래에서는 슬라이스(Slice)를 배열(Array)로 간주한다 +// Go에서 길이를 지정한 [5]int는 배열이고, 길이를 지정하지 않은 []int는 슬라이스다 +// Go의 배열은 컴파일 시점에 길이가 정해지도록 설계되어 있으므로 상수로만 길이를 지정할 수 있다 +// 용량을 늘리는 extend() 함수를 쉽게 구현하기 위해 아래에서는 슬라이스(Slice)를 배열(Array)로 취급한다 nums := []int{1, 3, 2, 5, 4} ``` ```swift title="array.swift" /* 배열 초기화 */ let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] -let nums = [1, 3, 2, 5, 4] +var nums = [1, 3, 2, 5, 4] ``` ```javascript title="array.js" /* 배열 초기화 */ -var arr = new Array(5).fill(0); -var nums = [1, 3, 2, 5, 4]; +const arr = new Array(5).fill(0); +let nums = [1, 3, 2, 5, 4]; ``` ```typescript title="array.ts" /* 배열 초기화 */ -let arr: number[] = new Array(5).fill(0); +const arr: number[] = new Array(5).fill(0); let nums: number[] = [1, 3, 2, 5, 4]; ``` ```dart title="array.dart" /* 배열 초기화 */ -List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +var arr = List.filled(5, 0); // [0, 0, 0, 0, 0] List nums = [1, 3, 2, 5, 4]; ``` ```rust title="array.rs" /* 배열 초기화 */ let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] -let slice: &[i32] = &[0; 5]; -// Rust에서 길이를 지정하면([i32; 5]) 배열이고, 지정하지 않으면(&[i32]) 슬라이스다 -// Rust 배열의 길이는 컴파일 시 결정되도록 설계되었으므로 상수로만 길이를 지정할 수 있다 +// Rust에서 길이를 지정한 [i32; 5]는 배열이고, 길이를 지정하지 않은 &[i32]는 슬라이스다 +// Rust의 배열은 컴파일 시점에 길이가 정해지도록 설계되어 있으므로 상수로만 길이를 지정할 수 있다 // Vector는 Rust에서 일반적으로 동적 배열로 사용하는 자료형이다 -// 용량 확장 메서드 extend()를 쉽게 구현하기 위해 아래에서는 vector를 배열(array)로 간주한다 +// 용량을 늘리는 extend() 메서드를 쉽게 구현하기 위해 아래에서는 vector를 배열(array)로 취급한다 let nums: Vec = vec![1, 3, 2, 5, 4]; ``` ```c title="array.c" /* 배열 초기화 */ -int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } -int nums[5] = { 1, 3, 2, 5, 4 }; +int arr[5] = {0}; // { 0, 0, 0, 0, 0 } +int nums[] = {1, 3, 2, 5, 4}; ``` ```kotlin title="array.kt" /* 배열 초기화 */ -var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +val arr = IntArray(5) // { 0, 0, 0, 0, 0 } var nums = intArrayOf(1, 3, 2, 5, 4) ``` diff --git a/ko/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/ko/codes/snippets/chapter_array_and_linkedlist/linked_list.md index fb2b6e5fd..20ed52306 100644 --- a/ko/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/ko/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -2,48 +2,53 @@ ```python title="" class ListNode: """연결 리스트 노드 클래스""" + def __init__(self, val: int): - self.val: int = val # 노드 값 - self.next: ListNode | None = None # 다음 노드를 가리키는 참조 + self.val: int = val # 노드 값 + self.next: ListNode | None = None # 다음 노드를 가리키는 참조 ``` ```cpp title="" -/* 연결 리스트 노드 구조체 */ +/* 연결 리스트 노드 */ struct ListNode { - int val; // 노드 값 - ListNode *next; // 다음 노드를 가리키는 포인터 - ListNode(int x) : val(x), next(nullptr) {} // 생성자 + int val; // 노드 값 + ListNode *next; // 다음 노드 포인터 + ListNode(int x) : val(x), next(nullptr) { + } }; ``` ```java title="" -/* 연결 리스트 노드 클래스 */ -class ListNode { - int val; // 노드 값 - ListNode next; // 다음 노드를 가리키는 참조 - ListNode(int x) { val = x; } // 생성자 +/* 연결 리스트 노드 */ +public class ListNode { + public int val; // 노드 값 + public ListNode next; // 다음 노드를 가리키는 참조 + + public ListNode(int x) { + val = x; + } } ``` ```csharp title="" -/* 연결 리스트 노드 클래스 */ -class ListNode(int x) { //생성자 - public int val = x; // 노드 값 - public ListNode? next; // 다음 노드를 가리키는 참조 +/* 연결 리스트 노드 */ +public class ListNode(int x) { + public int val = x; // 노드 값 + public ListNode? next; // 다음 노드를 가리키는 참조 } ``` ```go title="" -/* 연결 리스트 노드 구조체 */ +// ListNode: 연결 리스트 노드 type ListNode struct { Val int // 노드 값 - Next *ListNode // 다음 노드를 가리키는 포인터 + Next *ListNode // 다음 노드 포인터 } -// NewListNode 생성자: 새 연결 리스트 생성 -func NewListNode(val int) *ListNode { +// NewListNode: 연결 리스트 노드 생성자 +func NewListNode(v int) *ListNode { return &ListNode{ - Val: val, + Val: v, Next: nil, } } @@ -62,44 +67,54 @@ class ListNode { ``` ```javascript title="" -/* 연결 리스트 노드 클래스 */ +/* 연결 리스트 노드 */ class ListNode { + val; // 노드 값 + next; // 다음 노드를 가리키는 참조(포인터) constructor(val, next) { - this.val = (val === undefined ? 0 : val); // 노드 값 - this.next = (next === undefined ? null : next); // 다음 노드를 가리키는 참조 + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```typescript title="" -/* 연결 리스트 노드 클래스 */ +/* 연결 리스트 노드 */ class ListNode { - val: number; - next: ListNode | null; + val: number; // 노드 값 + next: ListNode | null; // 다음 노드를 가리키는 참조 constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.next = next === undefined ? null : next; // 다음 노드를 가리키는 참조 + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```dart title="" -/* 연결 리스트 노드 클래스 */ +/* 연결 리스트 노드 */ class ListNode { int val; // 노드 값 ListNode? next; // 다음 노드를 가리키는 참조 + ListNode(this.val, [this.next]); // 생성자 } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; -/* 연결 리스트 노드 클래스 */ +use std::rc::Rc; + +/* 연결 리스트 노드 */ #[derive(Debug)] -struct ListNode { - val: i32, // 노드 값 - next: Option>>, // 다음 노드를 가리키는 포인터 +pub struct ListNode { + pub val: T, // 노드 값 + pub next: Option>>>, // 다음 노드 포인터 +} + +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None })) + } } ``` @@ -110,10 +125,10 @@ typedef struct ListNode { struct ListNode *next; // 다음 노드를 가리키는 포인터 } ListNode; -/* 생성자 */ +/* 생성자: 새 노드를 초기화한다 */ ListNode *newListNode(int val) { ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); + node = (ListNode *)malloc(sizeof(ListNode)); node->val = val; node->next = NULL; return node; @@ -121,16 +136,14 @@ ListNode *newListNode(int val) { ``` ```kotlin title="" -/* 연결 리스트 노드 클래스 */ -// 생성자 -class ListNode(x: Int) { - val _val: Int = x // 노드 값 +/* 연결 리스트 노드 */ +class ListNode(var _val: Int) { var next: ListNode? = null // 다음 노드를 가리키는 참조 } ``` ```ruby title="" -# 연결 리스트 노드 클래스 +### 연결 리스트 노드 클래스 ### class ListNode attr_accessor :val # 노드 값 attr_accessor :next # 다음 노드를 가리키는 참조 @@ -145,13 +158,13 @@ end ```python title="linked_list.py" # 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 -# 각 노드 초기화 +# 각 노드를 초기화한다 n0 = ListNode(1) n1 = ListNode(3) n2 = ListNode(2) n3 = ListNode(5) n4 = ListNode(4) -# 노드 사이의 참조 설정 +# 노드 사이의 참조를 설정한다 n0.next = n1 n1.next = n2 n2.next = n3 @@ -160,13 +173,13 @@ n3.next = n4 ```cpp title="linked_list.cpp" /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 -ListNode* n0 = new ListNode(1); -ListNode* n1 = new ListNode(3); -ListNode* n2 = new ListNode(2); -ListNode* n3 = new ListNode(5); -ListNode* n4 = new ListNode(4); -// 노드 사이의 참조 설정 +// 각 노드를 초기화한다 +ListNode *n0 = new ListNode(1); +ListNode *n1 = new ListNode(3); +ListNode *n2 = new ListNode(2); +ListNode *n3 = new ListNode(5); +ListNode *n4 = new ListNode(4); +// 노드 사이의 참조를 설정한다 n0->next = n1; n1->next = n2; n2->next = n3; @@ -175,13 +188,13 @@ n3->next = n4; ```java title="linked_list.java" /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 +// 각 노드를 초기화한다 ListNode n0 = new ListNode(1); ListNode n1 = new ListNode(3); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(5); ListNode n4 = new ListNode(4); -// 노드 사이의 참조 설정 +// 노드 사이의 참조를 설정한다 n0.next = n1; n1.next = n2; n2.next = n3; @@ -189,14 +202,14 @@ n3.next = n4; ``` ```csharp title="linked_list.cs" -/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 +// 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 +// 각 노드를 초기화한다 ListNode n0 = new(1); ListNode n1 = new(3); ListNode n2 = new(2); ListNode n3 = new(5); ListNode n4 = new(4); -// 노드 사이의 참조 설정 +// 노드 사이의 참조를 설정한다 n0.next = n1; n1.next = n2; n2.next = n3; @@ -205,13 +218,14 @@ n3.next = n4; ```go title="linked_list.go" /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 +// 각 노드를 초기화한다 n0 := NewListNode(1) n1 := NewListNode(3) n2 := NewListNode(2) n3 := NewListNode(5) n4 := NewListNode(4) -// 노드 사이의 참조 설정 + +// 노드 사이의 참조를 설정한다 n0.Next = n1 n1.Next = n2 n2.Next = n3 @@ -220,13 +234,13 @@ n3.Next = n4 ```swift title="linked_list.swift" /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 +// 각 노드를 초기화한다 let n0 = ListNode(x: 1) let n1 = ListNode(x: 3) let n2 = ListNode(x: 2) let n3 = ListNode(x: 5) let n4 = ListNode(x: 4) -// 노드 사이의 참조 설정 +// 노드 사이의 참조를 설정한다 n0.next = n1 n1.next = n2 n2.next = n3 @@ -235,13 +249,13 @@ n3.next = n4 ```javascript title="linked_list.js" /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 +// 각 노드를 초기화한다 const n0 = new ListNode(1); const n1 = new ListNode(3); const n2 = new ListNode(2); const n3 = new ListNode(5); const n4 = new ListNode(4); -// 노드 사이의 참조 설정 +// 노드 사이의 참조를 설정한다 n0.next = n1; n1.next = n2; n2.next = n3; @@ -250,13 +264,13 @@ n3.next = n4; ```typescript title="linked_list.ts" /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 +// 각 노드를 초기화한다 const n0 = new ListNode(1); const n1 = new ListNode(3); const n2 = new ListNode(2); const n3 = new ListNode(5); const n4 = new ListNode(4); -// 노드 사이의 참조 설정 +// 노드 사이의 참조를 설정한다 n0.next = n1; n1.next = n2; n2.next = n3; @@ -264,14 +278,14 @@ n3.next = n4; ``` ```dart title="linked_list.dart" -/* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 +// 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 +// 각 노드를 초기화한다 ListNode n0 = ListNode(1); ListNode n1 = ListNode(3); ListNode n2 = ListNode(2); ListNode n3 = ListNode(5); ListNode n4 = ListNode(4); -// 노드 사이의 참조 설정 +// 노드 사이의 참조를 설정한다 n0.next = n1; n1.next = n2; n2.next = n3; @@ -280,14 +294,14 @@ n3.next = n4; ```rust title="linked_list.rs" /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 -let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); -let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); -let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); -let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); -let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); +// 각 노드를 초기화한다 +let n0 = ListNode::new(1); +let n1 = ListNode::new(3); +let n2 = ListNode::new(2); +let n3 = ListNode::new(5); +let n4 = ListNode::new(4); -// 노드 사이의 참조 설정 +// 노드 사이의 참조를 설정한다 n0.borrow_mut().next = Some(n1.clone()); n1.borrow_mut().next = Some(n2.clone()); n2.borrow_mut().next = Some(n3.clone()); @@ -296,13 +310,13 @@ n3.borrow_mut().next = Some(n4.clone()); ```c title="linked_list.c" /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 -ListNode* n0 = newListNode(1); -ListNode* n1 = newListNode(3); -ListNode* n2 = newListNode(2); -ListNode* n3 = newListNode(5); -ListNode* n4 = newListNode(4); -// 노드 사이의 참조 설정 +// 각 노드를 초기화한다 +ListNode *n0 = newListNode(1); +ListNode *n1 = newListNode(3); +ListNode *n2 = newListNode(2); +ListNode *n3 = newListNode(5); +ListNode *n4 = newListNode(4); +// 노드 사이의 참조를 설정한다 n0->next = n1; n1->next = n2; n2->next = n3; @@ -311,28 +325,29 @@ n3->next = n4; ```kotlin title="linked_list.kt" /* 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 */ -// 각 노드 초기화 +// 각 노드를 초기화한다 val n0 = ListNode(1) val n1 = ListNode(3) val n2 = ListNode(2) val n3 = ListNode(5) val n4 = ListNode(4) -// 노드 사이의 참조 설정 -n0.next = n1; -n1.next = n2; -n2.next = n3; -n3.next = n4; + +// 노드 사이의 참조를 설정한다 +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 ``` ```ruby title="linked_list.rb" # 연결 리스트 1 -> 3 -> 2 -> 5 -> 4 초기화 -# 각 노드 초기화 +# 각 노드를 초기화한다 n0 = ListNode.new(1) n1 = ListNode.new(3) n2 = ListNode.new(2) n3 = ListNode.new(5) n4 = ListNode.new(4) -# 노드 사이의 참조 설정 +# 노드 사이의 참조를 설정한다 n0.next = n1 n1.next = n2 n2.next = n3 @@ -345,39 +360,46 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2 ```python title="" class ListNode: - """이중 연결 리스트 노드 클래스""" + """이중 연결 리스트 노드""" + def __init__(self, val: int): - self.val: int = val # 노드 값 - self.next: ListNode | None = None # 후속 노드를 가리키는 참조 - self.prev: ListNode | None = None # 선행 노드를 가리키는 참조 + """생성자""" + self.val: int = val # 노드 값 + self.next: ListNode | None = None # 다음 노드 참조 + self.prev: ListNode | None = None # 이전 노드 참조 ``` ```cpp title="" -/* 이중 연결 리스트 노드 구조체 */ -struct ListNode { - int val; // 노드 값 - ListNode *next; // 후속 노드를 가리키는 포인터 - ListNode *prev; // 선행 노드를 가리키는 포인터 - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 생성자 +/* 이중 연결 리스트 노드 */ +struct DoublyListNode { + int val; // 노드 값 + DoublyListNode *next; // 다음 노드 포인터 + DoublyListNode *prev; // 이전 노드 포인터 + DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { + } }; ``` ```java title="" -/* 이중 연결 리스트 노드 클래스 */ +/* 이중 연결 리스트 노드 */ class ListNode { - int val; // 노드 값 - ListNode next; // 후속 노드를 가리키는 참조 - ListNode prev; // 선행 노드를 가리키는 참조 - ListNode(int x) { val = x; } // 생성자 + int val; // 노드 값 + ListNode next; // 다음 노드 참조 + ListNode prev; // 이전 노드 참조 + + ListNode(int val) { + this.val = val; + prev = next = null; + } } ``` ```csharp title="" -/* 이중 연결 리스트 노드 클래스 */ -class ListNode(int x) { // 생성자 - public int val = x; // 노드 값 - public ListNode? next; // 후속 노드를 가리키는 참조 - public ListNode? prev; // 선행 노드를 가리키는 참조 +/* 이중 연결 리스트 노드 */ +public class ListNode(int val) { + public int val = val; // 노드 값 + public ListNode? next = null; // 다음 노드 참조 + public ListNode? prev = null; // 이전 노드 참조 } ``` @@ -400,117 +422,119 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* 이중 연결 리스트 노드 클래스 */ +/* 이중 연결 리스트 노드 */ class ListNode { var val: Int // 노드 값 - var next: ListNode? // 후속 노드를 가리키는 참조 - var prev: ListNode? // 선행 노드를 가리키는 참조 + var next: ListNode? // 다음 노드 참조 + weak var prev: ListNode? // 이전 노드 참조 - init(x: Int) { // 생성자 - val = x + init(val: Int) { + self.val = val } } ``` ```javascript title="" -/* 이중 연결 리스트 노드 클래스 */ +/* 이중 연결 리스트 노드 */ class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.next = next === undefined ? null : next; // 후속 노드를 가리키는 참조 - this.prev = prev === undefined ? null : prev; // 선행 노드를 가리키는 참조 + prev; // 이전 노드 참조(포인터) + next; // 다음 노드 참조(포인터) + val; // 노드 값 + + constructor(val) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```typescript title="" -/* 이중 연결 리스트 노드 클래스 */ +/* 이중 연결 리스트 노드 */ class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.next = next === undefined ? null : next; // 후속 노드를 가리키는 참조 - this.prev = prev === undefined ? null : prev; // 선행 노드를 가리키는 참조 + prev: ListNode | null; // 이전 노드 참조(포인터) + next: ListNode | null; // 다음 노드 참조(포인터) + val: number; // 노드 값 + + constructor(val: number) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```dart title="" -/* 이중 연결 리스트 노드 클래스 */ +/* 이중 연결 리스트 노드 */ class ListNode { - int val; // 노드 값 - ListNode? next; // 후속 노드를 가리키는 참조 - ListNode? prev; // 선행 노드를 가리키는 참조 - ListNode(this.val, [this.next, this.prev]); // 생성자 + int val; // 노드 값 + ListNode? next; // 다음 노드 참조 + ListNode? prev; // 이전 노드 참조 + + ListNode(this.val, {this.next, this.prev}); } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; -/* 이중 연결 리스트 노드 자료형 */ -#[derive(Debug)] -struct ListNode { - val: i32, // 노드 값 - next: Option>>, // 후속 노드를 가리키는 포인터 - prev: Option>>, // 선행 노드를 가리키는 포인터 +/* 이중 연결 리스트 노드 */ +pub struct ListNode { + pub val: T, // 노드 값 + pub next: Option>>>, // 다음 노드 포인터 + pub prev: Option>>>, // 이전 노드 포인터 } -/* 생성자 */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None, prev: None, - } + })) } } ``` ```c title="" -/* 이중 연결 리스트 노드 구조체 */ -typedef struct ListNode { - int val; // 노드 값 - struct ListNode *next; // 후속 노드를 가리키는 포인터 - struct ListNode *prev; // 선행 노드를 가리키는 포인터 -} ListNode; +/* 이중 연결 리스트 노드 */ +typedef struct DoublyListNode { + int val; // 노드 값 + struct DoublyListNode *next; // 다음 노드 포인터 + struct DoublyListNode *prev; // 이전 노드 포인터 +} DoublyListNode; /* 생성자 */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; +DoublyListNode *newDoublyListNode(int num) { + DoublyListNode *new = (DoublyListNode *)malloc(sizeof(DoublyListNode)); + new->val = num; + new->next = NULL; + new->prev = NULL; + return new; } ``` ```kotlin title="" -/* 이중 연결 리스트 노드 클래스 */ -// 생성자 -class ListNode(x: Int) { - val _val: Int = x // 노드 값 - var next: ListNode? = null // 후속 노드를 가리키는 참조 - var prev: ListNode? = null // 선행 노드를 가리키는 참조 +/* 이중 연결 리스트 노드 */ +class ListNode( + var _val: Int // 노드 값 +) { + var next: ListNode? = null // 다음 노드 참조 + var prev: ListNode? = null // 이전 노드 참조 } ``` ```ruby title="" -# 이중 연결 리스트 노드 클래스 +### 이중 연결 리스트 노드 ### class ListNode - attr_accessor :val # 노드 값 - attr_accessor :next # 후속 노드를 가리키는 참조 - attr_accessor :prev # 선행 노드를 가리키는 참조 + attr_accessor :val # 노드 값 + attr_accessor :next # 다음 노드 참조 + attr_accessor :prev # 이전 노드 참조 - def initialize(val=0, next_node=nil, prev_node=nil) + ### 생성자 ### + def initialize(val) @val = val - @next = next_node - @prev = prev_node end end ``` diff --git a/ko/codes/snippets/chapter_array_and_linkedlist/list.md b/ko/codes/snippets/chapter_array_and_linkedlist/list.md index b5bd7958a..51ca7b2d8 100644 --- a/ko/codes/snippets/chapter_array_and_linkedlist/list.md +++ b/ko/codes/snippets/chapter_array_and_linkedlist/list.md @@ -2,25 +2,24 @@ ```python title="list.py" # 리스트 초기화 # 초깃값 없음 -nums1: list[int] = [] -# 초깃값 지정 +empty_nums: list[int] = [] +# 초깃값 있음 nums: list[int] = [1, 3, 2, 5, 4] ``` ```cpp title="list.cpp" /* 리스트 초기화 */ -// C++의 vector가 이 글에서 설명하는 nums에 해당한다 // 초깃값 없음 -vector nums1; -// 초깃값 지정 -vector nums = { 1, 3, 2, 5, 4 }; +vector emptyNums; +// 초깃값 있음 +vector nums = {1, 3, 2, 5, 4}; ``` ```java title="list.java" /* 리스트 초기화 */ // 초깃값 없음 -List nums1 = new ArrayList<>(); -// 초깃값 지정(배열은 int[]의 래퍼형인 Integer[]여야 함) +List emptyNums = new ArrayList<>(); +// 초깃값 있음(리스트 원소는 int의 래퍼 클래스인 Integer만 사용할 수 있으므로 배열 타입은 int[]가 아닌 Integer[]여야 한다는 점에 유의한다) Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); ``` @@ -28,8 +27,8 @@ List nums = new ArrayList<>(Arrays.asList(numbers)); ```csharp title="list.cs" /* 리스트 초기화 */ // 초깃값 없음 -List nums1 = []; -// 초깃값 지정 +List emptyNums = []; +// 초깃값 있음 int[] numbers = [1, 3, 2, 5, 4]; List nums = [.. numbers]; ``` @@ -37,48 +36,48 @@ List nums = [.. numbers]; ```go title="list_test.go" /* 리스트 초기화 */ // 초깃값 없음 -nums1 := []int{} -// 초깃값 지정 +emptyNums := []int{} +// 초깃값 있음 nums := []int{1, 3, 2, 5, 4} ``` ```swift title="list.swift" /* 리스트 초기화 */ // 초깃값 없음 -let nums1: [Int] = [] -// 초깃값 지정 +let emptyNums: [Int] = [] +// 초깃값 있음 var nums = [1, 3, 2, 5, 4] ``` ```javascript title="list.js" /* 리스트 초기화 */ // 초깃값 없음 -const nums1 = []; -// 초깃값 지정 +const emptyNums = []; +// 초깃값 있음 const nums = [1, 3, 2, 5, 4]; ``` ```typescript title="list.ts" /* 리스트 초기화 */ // 초깃값 없음 -const nums1: number[] = []; -// 초깃값 지정 +const emptyNums: number[] = []; +// 초깃값 있음 const nums: number[] = [1, 3, 2, 5, 4]; ``` ```dart title="list.dart" /* 리스트 초기화 */ // 초깃값 없음 -List nums1 = []; -// 초깃값 지정 +List emptyNums = []; +// 초깃값 있음 List nums = [1, 3, 2, 5, 4]; ``` ```rust title="list.rs" -/* 리스트 초기화 */ +// 리스트 초기화 // 초깃값 없음 -let nums1: Vec = Vec::new(); -// 초깃값 지정 +let empty_nums: Vec = Vec::new(); +// 초깃값 있음 let mut nums: Vec = vec![1, 3, 2, 5, 4]; ``` @@ -89,101 +88,101 @@ let mut nums: Vec = vec![1, 3, 2, 5, 4]; ```kotlin title="list.kt" /* 리스트 초기화 */ // 초깃값 없음 -var nums1 = listOf() -// 초깃값 지정 -var numbers = arrayOf(1, 3, 2, 5, 4) -var nums = numbers.toMutableList() +val emptyNums = mutableListOf() +// 초깃값 있음 +val nums = mutableListOf(1, 3, 2, 5, 4) ``` ```ruby title="list.rb" # 리스트 초기화 # 초깃값 없음 -nums1 = [] -# 초깃값 지정 +empty_nums = [] +# 초깃값 있음 nums = [1, 3, 2, 5, 4] ``` -https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%97%86%EC%9D%8C%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%A7%80%EC%A0%95%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%97%86%EC%9D%8C%0A%20%20%20%20empty_nums%20%3D%20%5B%5D%0A%20%20%20%20%23%20%EC%B4%88%EA%B9%83%EA%B0%92%20%EC%A7%80%EC%A0%95%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" # 원소 접근 -num: int = nums[1] # 인덱스 1의 원소에 접근 +x: int = nums[1] # 인덱스 1의 원소에 접근한다 # 원소 갱신 -nums[1] = 0 # 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0 # 인덱스 1의 원소를 0으로 갱신한다 ``` ```cpp title="list.cpp" /* 원소 접근 */ -int num = nums[1]; // 인덱스 1의 원소에 접근 +int num = nums[1]; // 인덱스 1의 원소에 접근한다 /* 원소 갱신 */ -nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신한다 ``` ```java title="list.java" /* 원소 접근 */ -int num = nums.get(1); // 인덱스 1의 원소에 접근 +int num = nums.get(1); // 인덱스 1의 원소에 접근한다 /* 원소 갱신 */ -nums.set(1, 0); // 인덱스 1의 원소를 0으로 갱신 +nums.set(1, 0); // 인덱스 1의 원소를 0으로 갱신한다 ``` ```csharp title="list.cs" /* 원소 접근 */ -int num = nums[1]; // 인덱스 1의 원소에 접근 +int num = nums[1]; // 인덱스 1의 원소에 접근한다 /* 원소 갱신 */ -nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신한다 ``` ```go title="list_test.go" /* 원소 접근 */ -num := nums[1] // 인덱스 1의 원소에 접근 +num := nums[1] // 인덱스 1의 원소에 접근한다 /* 원소 갱신 */ -nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신한다 ``` ```swift title="list.swift" /* 원소 접근 */ -let num = nums[1] // 인덱스 1의 원소에 접근 +let num = nums[1] // 인덱스 1의 원소에 접근한다 /* 원소 갱신 */ -nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신한다 ``` ```javascript title="list.js" /* 원소 접근 */ -const num = nums[1]; // 인덱스 1의 원소에 접근 +const num = nums[1]; // 인덱스 1의 원소에 접근한다 /* 원소 갱신 */ -nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신한다 ``` ```typescript title="list.ts" /* 원소 접근 */ -const num: number = nums[1]; // 인덱스 1의 원소에 접근 +const num: number = nums[1]; // 인덱스 1의 원소에 접근한다 /* 원소 갱신 */ -nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신한다 ``` ```dart title="list.dart" /* 원소 접근 */ -int num = nums[1]; // 인덱스 1의 원소에 접근 +int _num = nums[1]; // 인덱스 1의 원소에 접근한다 /* 원소 갱신 */ -nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신한다 ``` ```rust title="list.rs" -/* 원소 접근 */ -let num: i32 = nums[1]; // 인덱스 1의 원소에 접근 -/* 원소 갱신 */ -nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 +// 원소 접근 +let num = nums[1]; // 인덱스 1의 원소에 접근한다 + +// 원소 갱신 +nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신한다 ``` ```c title="list.c" @@ -192,27 +191,29 @@ nums[1] = 0; // 인덱스 1의 원소를 0으로 갱신 ```kotlin title="list.kt" /* 원소 접근 */ -val num = nums[1] // 인덱스 1의 원소에 접근 +val num = nums[1] // 인덱스 1의 원소에 접근한다 + /* 원소 갱신 */ -nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0 // 인덱스 1의 원소를 0으로 갱신한다 ``` ```ruby title="list.rb" # 원소 접근 -num = nums[1] # 인덱스 1의 원소에 접근 +num = nums[1] # 인덱스 1의 원소에 접근한다 + # 원소 갱신 -nums[1] = 0 # 인덱스 1의 원소를 0으로 갱신 +nums[1] = 0 # 인덱스 1의 원소를 0으로 갱신한다 ``` -https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%201%EC%9D%98%20%EC%9B%90%EC%86%8C%EC%97%90%20%EC%A0%91%EA%B7%BC%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EA%B0%B1%EC%8B%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%201%EC%9D%98%20%EC%9B%90%EC%86%8C%EB%A5%BC%200%EC%9C%BC%EB%A1%9C%20%EA%B0%B1%EC%8B%A0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EC%A0%91%EA%B7%BC%0A%20%20%20%20x%20%3D%20nums%5B1%5D%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%201%EC%9D%98%20%EC%9B%90%EC%86%8C%EC%97%90%20%EC%A0%91%EA%B7%BC%0A%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%20%EA%B0%B1%EC%8B%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%EC%9D%B8%EB%8D%B1%EC%8A%A4%201%EC%9D%98%20%EC%9B%90%EC%86%8C%EB%A5%BC%200%EC%9C%BC%EB%A1%9C%20%EA%B0%B1%EC%8B%A0&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" # 리스트 비우기 nums.clear() -# 끝에 원소 추가 +# 맨 뒤에 원소 추가 nums.append(1) nums.append(3) nums.append(2) @@ -220,17 +221,17 @@ nums.append(5) nums.append(4) # 중간에 원소 삽입 -nums.insert(3, 6) # 인덱스 3에 숫자 6 삽입 +nums.insert(3, 6) # 인덱스 3에 숫자 6을 삽입한다 # 원소 삭제 -nums.pop(3) # 인덱스 3의 원소 삭제 +nums.pop(3) # 인덱스 3의 원소를 삭제한다 ``` ```cpp title="list.cpp" /* 리스트 비우기 */ nums.clear(); -/* 끝에 원소 추가 */ +/* 맨 뒤에 원소 추가 */ nums.push_back(1); nums.push_back(3); nums.push_back(2); @@ -238,17 +239,17 @@ nums.push_back(5); nums.push_back(4); /* 중간에 원소 삽입 */ -nums.insert(nums.begin() + 3, 6); // 인덱스 3에 숫자 6 삽입 +nums.insert(nums.begin() + 3, 6); // 인덱스 3에 숫자 6을 삽입한다 /* 원소 삭제 */ -nums.erase(nums.begin() + 3); // 인덱스 3의 원소 삭제 +nums.erase(nums.begin() + 3); // 인덱스 3의 원소를 삭제한다 ``` ```java title="list.java" /* 리스트 비우기 */ nums.clear(); -/* 끝에 원소 추가 */ +/* 맨 뒤에 원소 추가 */ nums.add(1); nums.add(3); nums.add(2); @@ -256,17 +257,17 @@ nums.add(5); nums.add(4); /* 중간에 원소 삽입 */ -nums.add(3, 6); // 인덱스 3에 숫자 6 삽입 +nums.add(3, 6); // 인덱스 3에 숫자 6을 삽입한다 /* 원소 삭제 */ -nums.remove(3); // 인덱스 3의 원소 삭제 +nums.remove(3); // 인덱스 3의 원소를 삭제한다 ``` ```csharp title="list.cs" /* 리스트 비우기 */ nums.Clear(); -/* 끝에 원소 추가 */ +/* 맨 뒤에 원소 추가 */ nums.Add(1); nums.Add(3); nums.Add(2); @@ -274,17 +275,17 @@ nums.Add(5); nums.Add(4); /* 중간에 원소 삽입 */ -nums.Insert(3, 6); // 인덱스 3에 숫자 6 삽입 +nums.Insert(3, 6); // 인덱스 3에 숫자 6을 삽입한다 /* 원소 삭제 */ -nums.RemoveAt(3); // 인덱스 3의 원소 삭제 +nums.RemoveAt(3); // 인덱스 3의 원소를 삭제한다 ``` ```go title="list_test.go" /* 리스트 비우기 */ nums = nil -/* 끝에 원소 추가 */ +/* 맨 뒤에 원소 추가 */ nums = append(nums, 1) nums = append(nums, 3) nums = append(nums, 2) @@ -292,17 +293,17 @@ nums = append(nums, 5) nums = append(nums, 4) /* 중간에 원소 삽입 */ -nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 인덱스 3에 숫자 6 삽입 +nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 인덱스 3에 숫자 6을 삽입한다 /* 원소 삭제 */ -nums = append(nums[:3], nums[4:]...) // 인덱스 3의 원소 삭제 +nums = append(nums[:3], nums[4:]...) // 인덱스 3의 원소를 삭제한다 ``` ```swift title="list.swift" /* 리스트 비우기 */ nums.removeAll() -/* 끝에 원소 추가 */ +/* 맨 뒤에 원소 추가 */ nums.append(1) nums.append(3) nums.append(2) @@ -310,17 +311,17 @@ nums.append(5) nums.append(4) /* 중간에 원소 삽입 */ -nums.insert(6, at: 3) // 인덱스 3에 숫자 6 삽입 +nums.insert(6, at: 3) // 인덱스 3에 숫자 6을 삽입한다 /* 원소 삭제 */ -nums.remove(at: 3) // 인덱스 3의 원소 삭제 +nums.remove(at: 3) // 인덱스 3의 원소를 삭제한다 ``` ```javascript title="list.js" /* 리스트 비우기 */ nums.length = 0; -/* 끝에 원소 추가 */ +/* 맨 뒤에 원소 추가 */ nums.push(1); nums.push(3); nums.push(2); @@ -328,17 +329,17 @@ nums.push(5); nums.push(4); /* 중간에 원소 삽입 */ -nums.splice(3, 0, 6); // 인덱스 3에 숫자 6 삽입 +nums.splice(3, 0, 6); // 인덱스 3에 숫자 6을 삽입한다 /* 원소 삭제 */ -nums.splice(3, 1); // 인덱스 3의 원소 삭제 +nums.splice(3, 1); // 인덱스 3의 원소를 삭제한다 ``` ```typescript title="list.ts" /* 리스트 비우기 */ nums.length = 0; -/* 끝에 원소 추가 */ +/* 맨 뒤에 원소 추가 */ nums.push(1); nums.push(3); nums.push(2); @@ -346,17 +347,17 @@ nums.push(5); nums.push(4); /* 중간에 원소 삽입 */ -nums.splice(3, 0, 6); // 인덱스 3에 숫자 6 삽입 +nums.splice(3, 0, 6); // 인덱스 3에 숫자 6을 삽입한다 /* 원소 삭제 */ -nums.splice(3, 1); // 인덱스 3의 원소 삭제 +nums.splice(3, 1); // 인덱스 3의 원소를 삭제한다 ``` ```dart title="list.dart" /* 리스트 비우기 */ nums.clear(); -/* 끝에 원소 추가 */ +/* 맨 뒤에 원소 추가 */ nums.add(1); nums.add(3); nums.add(2); @@ -364,28 +365,28 @@ nums.add(5); nums.add(4); /* 중간에 원소 삽입 */ -nums.insert(3, 6); // 인덱스 3에 숫자 6 삽입 +nums.insert(3, 6); // 인덱스 3에 숫자 6을 삽입한다 /* 원소 삭제 */ -nums.removeAt(3); // 인덱스 3의 원소 삭제 +nums.removeAt(3); // 인덱스 3의 원소를 삭제한다 ``` ```rust title="list.rs" -/* 리스트 비우기 */ +// 리스트 비우기 nums.clear(); -/* 끝에 원소 추가 */ +// 맨 뒤에 원소 추가 nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* 중간에 원소 삽입 */ -nums.insert(3, 6); // 인덱스 3에 숫자 6 삽입 +// 중간에 원소 삽입 +nums.insert(3, 6); // 인덱스 3에 숫자 6을 삽입한다 -/* 원소 삭제 */ -nums.remove(3); // 인덱스 3의 원소 삭제 +// 원소 삭제 +nums.remove(3); // 인덱스 3의 원소를 삭제한다 ``` ```c title="list.c" @@ -394,27 +395,27 @@ nums.remove(3); // 인덱스 3의 원소 삭제 ```kotlin title="list.kt" /* 리스트 비우기 */ -nums.clear(); +nums.clear() -/* 끝에 원소 추가 */ -nums.add(1); -nums.add(3); -nums.add(2); -nums.add(5); -nums.add(4); +/* 맨 뒤에 원소 추가 */ +nums.add(1) +nums.add(3) +nums.add(2) +nums.add(5) +nums.add(4) /* 중간에 원소 삽입 */ -nums.add(3, 6); // 인덱스 3에 숫자 6 삽입 +nums.add(3, 6) // 인덱스 3에 숫자 6을 삽입한다 /* 원소 삭제 */ -nums.removeAt(3); // 인덱스 3의 원소 삭제 +nums.removeAt(3) // 인덱스 3의 원소를 삭제한다 ``` ```ruby title="list.rb" # 리스트 비우기 nums.clear -# 끝에 원소 추가 +# 맨 뒤에 원소 추가 nums << 1 nums << 3 nums << 2 @@ -422,10 +423,10 @@ nums << 5 nums << 4 # 중간에 원소 삽입 -nums.insert(3, 6) # 인덱스 3에 숫자 6 삽입 +nums.insert(3, 6) # 인덱스 3에 숫자 6을 삽입한다 # 원소 삭제 -nums.delete_at(3) # 인덱스 3의 원소 삭제 +nums.delete_at(3) # 인덱스 3의 원소를 삭제한다 ``` @@ -433,138 +434,138 @@ https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94 ```python title="list.py" -# 인덱스로 리스트 순회 +# 인덱스를 통해 리스트를 순회한다 count = 0 for i in range(len(nums)): count += nums[i] -# 리스트 원소를 직접 순회 +# 리스트의 원소를 직접 순회한다 for num in nums: count += num ``` ```cpp title="list.cpp" -/* 인덱스로 리스트 순회 */ +/* 인덱스를 통해 리스트를 순회한다 */ int count = 0; for (int i = 0; i < nums.size(); i++) { count += nums[i]; } -/* 리스트 원소를 직접 순회 */ +/* 리스트의 원소를 직접 순회한다 */ count = 0; -for (int num : nums) { - count += num; +for (int x : nums) { + count += x; } ``` ```java title="list.java" -/* 인덱스로 리스트 순회 */ +/* 인덱스를 통해 리스트를 순회한다 */ int count = 0; for (int i = 0; i < nums.size(); i++) { count += nums.get(i); } -/* 리스트 원소를 직접 순회 */ -for (int num : nums) { - count += num; +/* 리스트의 원소를 직접 순회한다 */ +for (int x : nums) { + count += x; } ``` ```csharp title="list.cs" -/* 인덱스로 리스트 순회 */ +/* 인덱스를 통해 리스트를 순회한다 */ int count = 0; for (int i = 0; i < nums.Count; i++) { count += nums[i]; } -/* 리스트 원소를 직접 순회 */ +/* 리스트의 원소를 직접 순회한다 */ count = 0; -foreach (int num in nums) { - count += num; +foreach (int x in nums) { + count += x; } ``` ```go title="list_test.go" -/* 인덱스로 리스트 순회 */ +/* 인덱스를 통해 리스트를 순회한다 */ count := 0 for i := 0; i < len(nums); i++ { count += nums[i] } -/* 리스트 원소를 직접 순회 */ +/* 리스트의 원소를 직접 순회한다 */ count = 0 -for _, num := range nums { - count += num +for _, x := range nums { + count += x } ``` ```swift title="list.swift" -/* 인덱스로 리스트 순회 */ +/* 인덱스를 통해 리스트를 순회한다 */ var count = 0 for i in nums.indices { count += nums[i] } -/* 리스트 원소를 직접 순회 */ +/* 리스트의 원소를 직접 순회한다 */ count = 0 -for num in nums { - count += num +for x in nums { + count += x } ``` ```javascript title="list.js" -/* 인덱스로 리스트 순회 */ +/* 인덱스를 통해 리스트를 순회한다 */ let count = 0; for (let i = 0; i < nums.length; i++) { count += nums[i]; } -/* 리스트 원소를 직접 순회 */ +/* 리스트의 원소를 직접 순회한다 */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` ```typescript title="list.ts" -/* 인덱스로 리스트 순회 */ +/* 인덱스를 통해 리스트를 순회한다 */ let count = 0; for (let i = 0; i < nums.length; i++) { count += nums[i]; } -/* 리스트 원소를 직접 순회 */ +/* 리스트의 원소를 직접 순회한다 */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` ```dart title="list.dart" -/* 인덱스로 리스트 순회 */ +/* 인덱스를 통해 리스트를 순회한다 */ int count = 0; for (var i = 0; i < nums.length; i++) { - count += nums[i]; + count += nums[i]; } -/* 리스트 원소를 직접 순회 */ +/* 리스트의 원소를 직접 순회한다 */ count = 0; -for (var num in nums) { - count += num; +for (var x in nums) { + count += x; } ``` ```rust title="list.rs" -// 인덱스로 리스트 순회 +// 인덱스를 통해 리스트를 순회한다 let mut _count = 0; for i in 0..nums.len() { _count += nums[i]; } -// 리스트 원소를 직접 순회 +// 리스트의 원소를 직접 순회한다 _count = 0; -for num in &nums { - _count += num; +for x in &nums { + _count += x; } ``` @@ -573,29 +574,29 @@ for num in &nums { ``` ```kotlin title="list.kt" -/* 인덱스로 리스트 순회 */ +/* 인덱스를 통해 리스트를 순회한다 */ var count = 0 for (i in nums.indices) { count += nums[i] } -/* 리스트 원소를 직접 순회 */ -for (num in nums) { - count += num +/* 리스트의 원소를 직접 순회한다 */ +for (j in nums) { + count += j } ``` ```ruby title="list.rb" -# 인덱스로 리스트 순회 +# 인덱스를 통해 리스트를 순회한다 count = 0 for i in 0...nums.length - count += nums[i] + count += nums[i] end -# 리스트 원소를 직접 순회 +# 리스트의 원소를 직접 순회한다 count = 0 -for num in nums - count += num +nums.each do |x| + count += x end ``` @@ -605,63 +606,63 @@ https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94 ```python title="list.py" # 두 리스트 연결 -nums1: list[int] = [6, 8, 7, 10, 9] -nums += nums1 # 리스트 nums1을 nums 뒤에 연결 +nums1 = [6, 8, 7, 10, 9] +nums += nums1 # 리스트 nums1을 nums 뒤에 연결한다 ``` ```cpp title="list.cpp" /* 두 리스트 연결 */ -vector nums1 = { 6, 8, 7, 10, 9 }; -// 리스트 nums1을 nums 뒤에 연결 +vector nums1 = {6, 8, 7, 10, 9}; +// 리스트 nums1을 nums 뒤에 연결한다 nums.insert(nums.end(), nums1.begin(), nums1.end()); ``` ```java title="list.java" /* 두 리스트 연결 */ List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); -nums.addAll(nums1); // 리스트 nums1을 nums 뒤에 연결 +nums.addAll(nums1); // 리스트 nums1을 nums 뒤에 연결한다 ``` ```csharp title="list.cs" /* 두 리스트 연결 */ List nums1 = [6, 8, 7, 10, 9]; -nums.AddRange(nums1); // 리스트 nums1을 nums 뒤에 연결 +nums.AddRange(nums1); // 리스트 nums1을 nums 뒤에 연결한다 ``` ```go title="list_test.go" /* 두 리스트 연결 */ nums1 := []int{6, 8, 7, 10, 9} -nums = append(nums, nums1...) // 리스트 nums1을 nums 뒤에 연결 +nums = append(nums, nums1...) // 리스트 nums1을 nums 뒤에 연결한다 ``` ```swift title="list.swift" /* 두 리스트 연결 */ let nums1 = [6, 8, 7, 10, 9] -nums.append(contentsOf: nums1) // 리스트 nums1을 nums 뒤에 연결 +nums.append(contentsOf: nums1) // 리스트 nums1을 nums 뒤에 연결한다 ``` ```javascript title="list.js" /* 두 리스트 연결 */ const nums1 = [6, 8, 7, 10, 9]; -nums.push(...nums1); // 리스트 nums1을 nums 뒤에 연결 +nums.push(...nums1); // 리스트 nums1을 nums 뒤에 연결한다 ``` ```typescript title="list.ts" /* 두 리스트 연결 */ const nums1: number[] = [6, 8, 7, 10, 9]; -nums.push(...nums1); // 리스트 nums1을 nums 뒤에 연결 +nums.push(...nums1); // 리스트 nums1을 nums 뒤에 연결한다 ``` ```dart title="list.dart" /* 두 리스트 연결 */ List nums1 = [6, 8, 7, 10, 9]; -nums.addAll(nums1); // 리스트 nums1을 nums 뒤에 연결 +nums.addAll(nums1); // 리스트 nums1을 nums 뒤에 연결한다 ``` ```rust title="list.rs" -/* 두 리스트 연결 */ -let nums1: Vec = vec![6, 8, 7, 10, 9]; -nums.extend(nums1); +// 두 리스트 연결 +let mut nums1 = vec![6, 8, 7, 10, 9]; +nums.append(&mut nums1); // append는 nums1의 원소를 이동시키므로 이후 nums1은 비게 된다 ``` ```c title="list.c" @@ -670,8 +671,8 @@ nums.extend(nums1); ```kotlin title="list.kt" /* 두 리스트 연결 */ -val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() -nums.addAll(nums1) // 리스트 nums1을 nums 뒤에 연결 +val nums1 = mutableListOf(6, 8, 7, 10, 9) +nums.addAll(nums1) // 리스트 nums1을 nums 뒤에 연결한다 ``` ```ruby title="list.rb" @@ -686,52 +687,52 @@ https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94 ```python title="list.py" # 리스트 정렬 -nums.sort() # 정렬 후 리스트 원소가 오름차순으로 배치됨 +nums.sort() # 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```cpp title="list.cpp" /* 리스트 정렬 */ -sort(nums.begin(), nums.end()); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +sort(nums.begin(), nums.end()); // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```java title="list.java" /* 리스트 정렬 */ -Collections.sort(nums); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +Collections.sort(nums); // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```csharp title="list.cs" /* 리스트 정렬 */ -nums.Sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +nums.Sort(); // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```go title="list_test.go" /* 리스트 정렬 */ -sort.Ints(nums) // 정렬 후 리스트 원소가 오름차순으로 배치됨 +sort.Ints(nums) // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```swift title="list.swift" /* 리스트 정렬 */ -nums.sort() // 정렬 후 리스트 원소가 오름차순으로 배치됨 +nums.sort() // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```javascript title="list.js" /* 리스트 정렬 */ -nums.sort((a, b) => a - b); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +nums.sort((a, b) => a - b); // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```typescript title="list.ts" /* 리스트 정렬 */ -nums.sort((a, b) => a - b); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +nums.sort((a, b) => a - b); // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```dart title="list.dart" /* 리스트 정렬 */ -nums.sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +nums.sort(); // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```rust title="list.rs" -/* 리스트 정렬 */ -nums.sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 +// 리스트 정렬 +nums.sort(); // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```c title="list.c" @@ -740,12 +741,12 @@ nums.sort(); // 정렬 후 리스트 원소가 오름차순으로 배치됨 ```kotlin title="list.kt" /* 리스트 정렬 */ -nums.sort() // 정렬 후 리스트 원소가 오름차순으로 배치됨 +nums.sort() // 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` ```ruby title="list.rb" # 리스트 정렬 -nums = nums.sort { |a, b| a <=> b } # 정렬 후 리스트 원소가 오름차순으로 배치됨 +nums = nums.sort { |a, b| a <=> b } # 정렬 후 리스트 원소는 작은 값부터 큰 값 순서로 나열된다 ``` diff --git a/ko/codes/snippets/chapter_hashing/hash_algorithm.md b/ko/codes/snippets/chapter_hashing/hash_algorithm.md index 928219822..1910ed7e1 100644 --- a/ko/codes/snippets/chapter_hashing/hash_algorithm.md +++ b/ko/codes/snippets/chapter_hashing/hash_algorithm.md @@ -2,100 +2,122 @@ ```python title="built_in_hash.py" num = 3 hash_num = hash(num) -# 정수 3의 해시값은 3 +print(f"정수 {num} → 해시값: {hash_num}") +# 정수 3 → 해시값: 3 bol = True hash_bol = hash(bol) -# 불리언 True의 해시값은 1 +print(f"불리언 값 {bol} → 해시값: {hash_bol}") +# 불리언 값 True → 해시값: 1 dec = 3.14159 hash_dec = hash(dec) -# 소수 3.14159의 해시값은 326484311674566659 +print(f"소수 {dec} → 해시값: {hash_dec}") +# 소수 3.14159 → 해시값: 326484311674566659 str = "Hello 算法" hash_str = hash(str) -# 문자열 “Hello 算法”의 해시값은 4617003410720528961 +print(f"문자열 ‘{str}’ → 해시값: {hash_str}") +# 문자열 ‘Hello 算法’ → 해시값: 4617003410720528961 tup = (12836, "小哈") hash_tup = hash(tup) -# 튜플 (12836, '小哈')의 해시값은 1029005403108185979 +print(f"튜플 {tup} → 해시값: {hash_tup}") +# 튜플 (12836, '小哈') → 해시값: 1029005403108185979 obj = ListNode(0) hash_obj = hash(obj) -# 노드 객체 의 해시값은 274267521 +print(f"노드 객체 {obj} → 해시값: {hash_obj}") +# 노드 객체 → 해시값: 274267521 ``` ```cpp title="built_in_hash.cpp" int num = 3; size_t hashNum = hash()(num); -// 정수 3의 해시값은 3 +cout << "정수 " << num << " → 해시값: " << hashNum << "\n"; +// 정수 3 → 해시값: 3 bool bol = true; size_t hashBol = hash()(bol); -// 불리언 1의 해시값은 1 +cout << "불리언 값 " << bol << " → 해시값: " << hashBol << "\n"; +// 불리언 값 1 → 해시값: 1 double dec = 3.14159; size_t hashDec = hash()(dec); -// 소수 3.14159의 해시값은 4614256650576692846 +cout << "소수 " << dec << " → 해시값: " << hashDec << "\n"; +// 소수 3.14159 → 해시값: 4614256650576692846 string str = "Hello 算法"; size_t hashStr = hash()(str); -// 문자열 “Hello 算法”의 해시값은 15466937326284535026 +cout << "문자열 ‘" << str << "’ → 해시값: " << hashStr << "\n"; +// 문자열 ‘Hello 算法’ → 해시값: 15466937326284535026 -// C++의 내장 std::hash()는 기본 자료형의 해시값 계산만 제공한다 +// C++의 내장 std::hash()는 기본 데이터 타입에 대한 해시값 계산만 제공한다 // 배열과 객체의 해시값 계산은 직접 구현해야 한다 ``` ```java title="built_in_hash.java" int num = 3; int hashNum = Integer.hashCode(num); -// 정수 3의 해시값은 3 +System.out.println("정수 " + num + " → 해시값: " + hashNum); +// 정수 3 → 해시값: 3 boolean bol = true; int hashBol = Boolean.hashCode(bol); -// 불리언 true의 해시값은 1231 +System.out.println("불리언 값 " + bol + " → 해시값: " + hashBol); +// 불리언 값 true → 해시값: 1231 double dec = 3.14159; int hashDec = Double.hashCode(dec); -// 소수 3.14159의 해시값은 -1340954729 +System.out.println("소수 " + dec + " → 해시값: " + hashDec); +// 소수 3.14159 → 해시값: -1340954729 String str = "Hello 算法"; int hashStr = str.hashCode(); -// 문자열 “Hello 算法”의 해시값은 -727081396 +System.out.println("문자열 ‘" + str + "’ → 해시값: " + hashStr); +// 문자열 ‘Hello 算法’ → 해시값: -727081396 Object[] arr = { 12836, "小哈" }; -int hashTup = Arrays.hashCode(arr); -// 배열 [12836, 小哈]의 해시값은 1151158 +int hashArr = Arrays.hashCode(arr); +System.out.println("배열 " + Arrays.toString(arr) + " → 해시값: " + hashArr); +// 배열 [12836, 小哈] → 해시값: 1151158 ListNode obj = new ListNode(0); int hashObj = obj.hashCode(); -// 노드 객체 utils.ListNode@7dc5e7b4의 해시값은 2110121908 +System.out.println("노드 객체 " + obj + " → 해시값: " + hashObj); +// 노드 객체 utils.ListNode@7dc5e7b4 → 해시값: 2110121908 ``` ```csharp title="built_in_hash.cs" int num = 3; int hashNum = num.GetHashCode(); -// 정수 3의 해시값은 3; +Console.WriteLine("정수 " + num + " → 해시값: " + hashNum); +// 정수 3 → 해시값: 3 bool bol = true; int hashBol = bol.GetHashCode(); -// 불리언 true의 해시값은 1; +Console.WriteLine("불리언 값 " + bol + " → 해시값: " + hashBol); +// 불리언 값 True → 해시값: 1 double dec = 3.14159; int hashDec = dec.GetHashCode(); -// 소수 3.14159의 해시값은 -1340954729; +Console.WriteLine("소수 " + dec + " → 해시값: " + hashDec); +// 소수 3.14159 → 해시값: -1340954729 string str = "Hello 算法"; int hashStr = str.GetHashCode(); -// 문자열 “Hello 算法”의 해시값은 -586107568; +Console.WriteLine("문자열 ‘" + str + "’ → 해시값: " + hashStr); +// 문자열 ‘Hello 算法’ → 해시값: -586107568 object[] arr = [12836, "小哈"]; -int hashTup = arr.GetHashCode(); -// 배열 [12836, 小哈]의 해시값은 42931033; +int hashArr = arr.GetHashCode(); +Console.WriteLine("배열 [" + string.Join(", ", arr) + "] → 해시값: " + hashArr); +// 배열 [12836, 小哈] → 해시값: 42931033 ListNode obj = new(0); int hashObj = obj.GetHashCode(); -// 노드 객체 0의 해시값은 39053774; +Console.WriteLine("노드 객체 " + obj + " → 해시값: " + hashObj); +// 노드 객체 0 → 해시값: 39053774 ``` ```go title="built_in_hash.go" @@ -105,27 +127,33 @@ int hashObj = obj.GetHashCode(); ```swift title="built_in_hash.swift" let num = 3 let hashNum = num.hashValue -// 정수 3의 해시값은 9047044699613009734 +print("정수 \(num) → 해시값: \(hashNum)") +// 정수 3 → 해시값: 9047044699613009734 let bol = true let hashBol = bol.hashValue -// 불리언 true의 해시값은 -4431640247352757451 +print("불리언 값 \(bol) → 해시값: \(hashBol)") +// 불리언 값 true → 해시값: -4431640247352757451 let dec = 3.14159 let hashDec = dec.hashValue -// 소수 3.14159의 해시값은 -2465384235396674631 +print("소수 \(dec) → 해시값: \(hashDec)") +// 소수 3.14159 → 해시값: -2465384235396674631 let str = "Hello 算法" let hashStr = str.hashValue -// 문자열 “Hello 算法”의 해시값은 -7850626797806988787 +print("문자열 ‘\(str)’ → 해시값: \(hashStr)") +// 문자열 ‘Hello 算法’ → 해시값: -7850626797806988787 let arr = [AnyHashable(12836), AnyHashable("小哈")] -let hashTup = arr.hashValue -// 배열 [AnyHashable(12836), AnyHashable("小哈")]의 해시값은 -2308633508154532996 +let hashArr = arr.hashValue +print("배열 \(arr) → 해시값: \(hashArr)") +// 배열 [AnyHashable(12836), AnyHashable("小哈")] → 해시값: -2308633508154532996 let obj = ListNode(x: 0) let hashObj = obj.hashValue -// 노드 객체 utils.ListNode의 해시값은 -2434780518035996159 +print("노드 객체 \(obj) → 해시값: \(hashObj)") +// 노드 객체 utils.ListNode → 해시값: -2434780518035996159 ``` ```javascript title="built_in_hash.js" @@ -139,27 +167,33 @@ let hashObj = obj.hashValue ```dart title="built_in_hash.dart" int num = 3; int hashNum = num.hashCode; -// 정수 3의 해시값은 34803 +print("정수 $num → 해시값: $hashNum"); +// 정수 3 → 해시값: 34803 bool bol = true; int hashBol = bol.hashCode; -// 불리언 true의 해시값은 1231 +print("불리언 값 $bol → 해시값: $hashBol"); +// 불리언 값 true → 해시값: 1231 double dec = 3.14159; int hashDec = dec.hashCode; -// 소수 3.14159의 해시값은 2570631074981783 +print("소수 $dec → 해시값: $hashDec"); +// 소수 3.14159 → 해시값: 2570631074981783 String str = "Hello 算法"; int hashStr = str.hashCode; -// 문자열 “Hello 算法”의 해시값은 468167534 +print("문자열 ‘$str’ → 해시값: $hashStr"); +// 문자열 ‘Hello 算法’ → 해시값: 468167534 List arr = [12836, "小哈"]; int hashArr = arr.hashCode; -// 배열 [12836, 小哈]의 해시값은 976512528 +print("배열 $arr → 해시값: $hashArr"); +// 배열 [12836, 小哈] → 해시값: 976512528 -ListNode obj = new ListNode(0); +ListNode obj = ListNode(0); int hashObj = obj.hashCode; -// 노드 객체 Instance of 'ListNode'의 해시값은 1033450432 +print("노드 객체 $obj → 해시값: $hashObj"); +// 노드 객체 Instance of 'ListNode' → 해시값: 1033450432 ``` ```rust title="built_in_hash.rs" @@ -170,37 +204,43 @@ let num = 3; let mut num_hasher = DefaultHasher::new(); num.hash(&mut num_hasher); let hash_num = num_hasher.finish(); -// 정수 3의 해시값은 568126464209439262 +println!("정수 {} → 해시값: {}", num, hash_num); +// 정수 3 → 해시값: 568126464209439262 let bol = true; let mut bol_hasher = DefaultHasher::new(); bol.hash(&mut bol_hasher); let hash_bol = bol_hasher.finish(); -// 불리언 true의 해시값은 4952851536318644461 +println!("불리언 값 {} → 해시값: {}", bol, hash_bol); +// 불리언 값 true → 해시값: 4952851536318644461 let dec: f32 = 3.14159; let mut dec_hasher = DefaultHasher::new(); dec.to_bits().hash(&mut dec_hasher); let hash_dec = dec_hasher.finish(); -// 소수 3.14159의 해시값은 2566941990314602357 +println!("소수 {} → 해시값: {}", dec, hash_dec); +// 소수 3.14159 → 해시값: 2566941990314602357 let str = "Hello 算法"; let mut str_hasher = DefaultHasher::new(); str.hash(&mut str_hasher); let hash_str = str_hasher.finish(); -// 문자열 “Hello 算法”의 해시값은 16092673739211250988 +println!("문자열 ‘{}’ → 해시값: {}", str, hash_str); +// 문자열 ‘Hello 算法’ → 해시값: 16092673739211250988 -let arr = (&12836, &"小哈"); +let tup = (&12836, &"小哈"); let mut tup_hasher = DefaultHasher::new(); -arr.hash(&mut tup_hasher); +tup.hash(&mut tup_hasher); let hash_tup = tup_hasher.finish(); -// 튜플 (12836, "小哈")의 해시값은 1885128010422702749 +println!("튜플 {:?} → 해시값: {}", tup, hash_tup); +// 튜플 (12836, "小哈") → 해시값: 1885128010422702749 let node = ListNode::new(42); -let mut hasher = DefaultHasher::new(); -node.borrow().val.hash(&mut hasher); -let hash = hasher.finish(); -// 노드 객체 RefCell { value: ListNode { val: 42, next: None } }의 해시값은 15387811073369036852 +let mut node_hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut node_hasher); +let hash_node = node_hasher.finish(); +println!("노드 객체 {:?} → 해시값: {}", node, hash_node); +// 노드 객체 RefCell { value: ListNode { val: 42, next: None } } → 해시값: 15387811073369036852 ``` ```c title="built_in_hash.c" @@ -210,54 +250,66 @@ let hash = hasher.finish(); ```kotlin title="built_in_hash.kt" val num = 3 val hashNum = num.hashCode() -// 정수 3의 해시값은 3 +println("정수 $num → 해시값: $hashNum") +// 정수 3 → 해시값: 3 val bol = true val hashBol = bol.hashCode() -// 불리언 true의 해시값은 1231 +println("불리언 값 $bol → 해시값: $hashBol") +// 불리언 값 true → 해시값: 1231 val dec = 3.14159 val hashDec = dec.hashCode() -// 소수 3.14159의 해시값은 -1340954729 +println("소수 $dec → 해시값: $hashDec") +// 소수 3.14159 → 해시값: -1340954729 val str = "Hello 算法" val hashStr = str.hashCode() -// 문자열 “Hello 算法”의 해시값은 -727081396 +println("문자열 ‘$str’ → 해시값: $hashStr") +// 문자열 ‘Hello 算法’ → 해시값: -727081396 val arr = arrayOf(12836, "小哈") -val hashTup = arr.hashCode() -// 배열 [12836, 小哈]의 해시값은 189568618 +val hashArr = arr.contentHashCode() +println("배열 ${arr.contentToString()} → 해시값: $hashArr") +// 배열 [12836, 小哈] → 해시값: 1151158 val obj = ListNode(0) val hashObj = obj.hashCode() -// 노드 객체 utils.ListNode@1d81eb93의 해시값은 495053715 +println("노드 객체 $obj → 해시값: $hashObj") +// 노드 객체 utils.ListNode@1d81eb93 → 해시값: 495053715 ``` ```ruby title="built_in_hash.rb" num = 3 hash_num = num.hash -# 정수 3의 해시값은 -4385856518450339636 +puts "정수 #{num} → 해시값: #{hash_num}" +# 정수 3 → 해시값: -4385856518450339636 bol = true hash_bol = bol.hash -# 불리언 true의 해시값은 -1617938112149317027 +puts "불리언 값 #{bol} → 해시값: #{hash_bol}" +# 불리언 값 true → 해시값: -1617938112149317027 dec = 3.14159 hash_dec = dec.hash -# 소수 3.14159의 해시값은 -1479186995943067893 +puts "소수 #{dec} → 해시값: #{hash_dec}" +# 소수 3.14159 → 해시값: -1479186995943067893 str = "Hello 算法" hash_str = str.hash -# 문자열 “Hello 算法”의 해시값은 -4075943250025831763 +puts "문자열 ‘#{str}’ → 해시값: #{hash_str}" +# 문자열 ‘Hello 算法’ → 해시값: -4075943250025831763 -tup = [12836, '小哈'] -hash_tup = tup.hash -# 튜플 (12836, '小哈')의 해시값은 1999544809202288822 +arr = [12836, '小哈'] +hash_arr = arr.hash +puts "배열 #{arr} → 해시값: #{hash_arr}" +# 배열 [12836, "小哈"] → 해시값: 1999544809202288822 obj = ListNode.new(0) hash_obj = obj.hash -# 노드 객체 #의 해시값은 4302940560806366381 +puts "노드 객체 #{obj} → 해시값: #{hash_obj}" +# 노드 객체 # → 해시값: 4302940560806366381 ``` -https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%ED%9B%84%EC%86%8D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%EC%A0%95%EC%88%98%203%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%EB%B6%88%EB%A6%AC%EC%96%B8%20True%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%EC%86%8C%EC%88%98%203.14159%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%EB%AC%B8%EC%9E%90%EC%97%B4%20%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%ED%8A%9C%ED%94%8C%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%9D%EC%B2%B4%20%3CListNode%20object%20at%200x1058fd810%3E%EC%9D%98%20%ED%95%B4%EC%8B%9C%EA%B0%92%EC%9D%80%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%EC%97%B0%EA%B2%B0%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%ED%9B%84%EC%86%8D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20print%28f%22%EC%A0%95%EC%88%98%20%7Bnum%7D%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%20%7Bhash_num%7D%22%29%0A%20%20%20%20%23%20%EC%A0%95%EC%88%98%203%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20print%28f%22%EB%B6%88%EB%A6%AC%EC%96%B8%20%EA%B0%92%20%7Bbol%7D%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%20%7Bhash_bol%7D%22%29%0A%20%20%20%20%23%20%EB%B6%88%EB%A6%AC%EC%96%B8%20%EA%B0%92%20True%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20print%28f%22%EC%86%8C%EC%88%98%20%7Bdec%7D%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%20%7Bhash_dec%7D%22%29%0A%20%20%20%20%23%20%EC%86%8C%EC%88%98%203.14159%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20print%28f%22%EB%AC%B8%EC%9E%90%EC%97%B4%20%E2%80%98%7Bstr%7D%E2%80%99%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%20%7Bhash_str%7D%22%29%0A%20%20%20%20%23%20%EB%AC%B8%EC%9E%90%EC%97%B4%20%E2%80%98Hello%20%E7%AE%97%E6%B3%95%E2%80%99%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20print%28f%22%ED%8A%9C%ED%94%8C%20%7Btup%7D%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%20%7Bhash_tup%7D%22%29%0A%20%20%20%20%23%20%ED%8A%9C%ED%94%8C%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20print%28f%22%EB%85%B8%EB%93%9C%20%EA%B0%9D%EC%B2%B4%20%7Bobj%7D%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%20%7Bhash_obj%7D%22%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%9D%EC%B2%B4%20%3Cmodules.list_node.ListNode%20object%20at%200x1058fd810%3E%20%E2%86%92%20%ED%95%B4%EC%8B%9C%EA%B0%92%3A%20274267521%0A&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_hashing/hash_map.md b/ko/codes/snippets/chapter_hashing/hash_map.md index 0257348e1..aa82f1a56 100644 --- a/ko/codes/snippets/chapter_hashing/hash_map.md +++ b/ko/codes/snippets/chapter_hashing/hash_map.md @@ -1,10 +1,10 @@ ```python title="hash_map.py" # 해시 테이블 초기화 -hmap: dict = {} +hmap = dict[int, str]() # 추가 연산 -# 해시 테이블에 키-값 쌍 (key, value) 추가 +# 해시 테이블에 (key, value) 키-값 쌍을 추가한다 hmap[12836] = "小哈" hmap[15937] = "小啰" hmap[16750] = "小算" @@ -12,11 +12,11 @@ hmap[13276] = "小法" hmap[10583] = "小鸭" # 조회 연산 -# 해시 테이블에 키 key를 입력하여 값 value를 얻음 +# 해시 테이블에 키 key를 입력하여 값 value를 얻는다 name: str = hmap[15937] # 삭제 연산 -# 해시 테이블에서 키-값 쌍 (key, value) 삭제 +# 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 hmap.pop(10583) ``` @@ -25,7 +25,7 @@ hmap.pop(10583) unordered_map map; /* 추가 연산 */ -// 해시 테이블에 키-값 쌍 (key, value) 추가 +// 해시 테이블에 (key, value) 키-값 쌍을 추가한다 map[12836] = "小哈"; map[15937] = "小啰"; map[16750] = "小算"; @@ -33,11 +33,11 @@ map[13276] = "小法"; map[10583] = "小鸭"; /* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 string name = map[15937]; /* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 map.erase(10583); ``` @@ -46,7 +46,7 @@ map.erase(10583); Map map = new HashMap<>(); /* 추가 연산 */ -// 해시 테이블에 키-값 쌍 (key, value) 추가 +// 해시 테이블에 (key, value) 키-값 쌍을 추가한다 map.put(12836, "小哈"); map.put(15937, "小啰"); map.put(16750, "小算"); @@ -54,11 +54,11 @@ map.put(13276, "小法"); map.put(10583, "小鸭"); /* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 String name = map.get(15937); /* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 map.remove(10583); ``` @@ -66,7 +66,7 @@ map.remove(10583); /* 해시 테이블 초기화 */ Dictionary map = new() { /* 추가 연산 */ - // 해시 테이블에 키-값 쌍 (key, value) 추가 + // 해시 테이블에 (key, value) 키-값 쌍을 추가한다 { 12836, "小哈" }, { 15937, "小啰" }, { 16750, "小算" }, @@ -75,11 +75,11 @@ Dictionary map = new() { }; /* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 string name = map[15937]; /* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 map.Remove(10583); ``` @@ -88,7 +88,7 @@ map.Remove(10583); hmap := make(map[int]string) /* 추가 연산 */ -// 해시 테이블에 키-값 쌍 (key, value) 추가 +// 해시 테이블에 (key, value) 키-값 쌍을 추가한다 hmap[12836] = "小哈" hmap[15937] = "小啰" hmap[16750] = "小算" @@ -96,11 +96,11 @@ hmap[13276] = "小法" hmap[10583] = "小鸭" /* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 name := hmap[15937] /* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 delete(hmap, 10583) ``` @@ -109,7 +109,7 @@ delete(hmap, 10583) var map: [Int: String] = [:] /* 추가 연산 */ -// 해시 테이블에 키-값 쌍 (key, value) 추가 +// 해시 테이블에 (key, value) 키-값 쌍을 추가한다 map[12836] = "小哈" map[15937] = "小啰" map[16750] = "小算" @@ -117,19 +117,20 @@ map[13276] = "小法" map[10583] = "小鸭" /* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 let name = map[15937]! /* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 map.removeValue(forKey: 10583) ``` ```javascript title="hash_map.js" /* 해시 테이블 초기화 */ const map = new Map(); + /* 추가 연산 */ -// 해시 테이블에 키-값 쌍 (key, value) 추가 +// 해시 테이블에 (key, value) 키-값 쌍을 추가한다 map.set(12836, '小哈'); map.set(15937, '小啰'); map.set(16750, '小算'); @@ -137,45 +138,41 @@ map.set(13276, '小法'); map.set(10583, '小鸭'); /* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 let name = map.get(15937); /* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 map.delete(10583); ``` ```typescript title="hash_map.ts" /* 해시 테이블 초기화 */ const map = new Map(); + /* 추가 연산 */ -// 해시 테이블에 키-값 쌍 (key, value) 추가 +// 해시 테이블에 (key, value) 키-값 쌍을 추가한다 map.set(12836, '小哈'); map.set(15937, '小啰'); map.set(16750, '小算'); map.set(13276, '小法'); map.set(10583, '小鸭'); -console.info('\n추가한 뒤의 해시 테이블\nKey -> Value'); -console.info(map); /* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 let name = map.get(15937); -console.info('\n학번 15937을 입력하여 찾은 이름 ' + name); /* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 map.delete(10583); -console.info('\n10583을 삭제한 뒤의 해시 테이블\nKey -> Value'); -console.info(map); ``` ```dart title="hash_map.dart" /* 해시 테이블 초기화 */ -Map map = {}; +final Map map = {}; /* 추가 연산 */ -// 해시 테이블에 키-값 쌍 (key, value) 추가 +// 해시 테이블에 (key, value) 키-값 쌍을 추가한다 map[12836] = "小哈"; map[15937] = "小啰"; map[16750] = "小算"; @@ -183,35 +180,35 @@ map[13276] = "小法"; map[10583] = "小鸭"; /* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 -String? name = map[15937]; +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 +final String? name = map[15937]; /* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 map.remove(10583); ``` ```rust title="hash_map.rs" use std::collections::HashMap; -/* 해시 테이블 초기화 */ -let mut map: HashMap = HashMap::new(); +// 해시 테이블 초기화 +let mut map = HashMap::new(); -/* 추가 연산 */ -// 해시 테이블에 키-값 쌍 (key, value) 추가 -map.insert(12836, "小哈".to_string()); -map.insert(15937, "小啰".to_string()); -map.insert(16750, "小算".to_string()); -map.insert(13276, "小法".to_string()); -map.insert(10583, "小鸭".to_string()); +// 추가 연산 +// 해시 테이블에 (key, value) 키-값 쌍을 추가한다 +map.insert(12836, "小哈"); +map.insert(15937, "小啰"); +map.insert(16750, "小算"); +map.insert(13276, "小法"); +map.insert(10583, "小鸭"); -/* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 -let _name: Option<&String> = map.get(&15937); +// 조회 연산 +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 +let name = map.get(&15937).copied().unwrap(); -/* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 -let _removed_value: Option = map.remove(&10583); +// 삭제 연산 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 +_ = map.remove(&10583); ``` ```c title="hash_map.c" @@ -220,10 +217,10 @@ let _removed_value: Option = map.remove(&10583); ```kotlin title="hash_map.kt" /* 해시 테이블 초기화 */ -val map = HashMap() +val map = HashMap() /* 추가 연산 */ -// 해시 테이블에 키-값 쌍 (key, value) 추가 +// 해시 테이블에 (key, value) 키-값 쌍을 추가한다 map[12836] = "小哈" map[15937] = "小啰" map[16750] = "小算" @@ -231,11 +228,11 @@ map[13276] = "小法" map[10583] = "小鸭" /* 조회 연산 */ -// 해시 테이블에 키 key를 입력하여 값 value를 얻음 +// 해시 테이블에 키 key를 입력하여 값 value를 얻는다 val name = map[15937] /* 삭제 연산 */ -// 해시 테이블에서 키-값 쌍 (key, value) 삭제 +// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 map.remove(10583) ``` @@ -244,7 +241,7 @@ map.remove(10583) hmap = {} # 추가 연산 -# 해시 테이블에 키-값 쌍 (key, value) 추가 +# 해시 테이블에 (key, value) 키-값 쌍을 추가한다 hmap[12836] = "小哈" hmap[15937] = "小啰" hmap[16750] = "小算" @@ -252,11 +249,11 @@ hmap[13276] = "小法" hmap[10583] = "小鸭" # 조회 연산 -# 해시 테이블에 키 key를 입력하여 값 value를 얻음 +# 해시 테이블에 키 key를 입력하여 값 value를 얻는다 name = hmap[15937] # 삭제 연산 -# 해시 테이블에서 키-값 쌍 (key, value) 삭제 +# 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다 hmap.delete(10583) ``` @@ -266,56 +263,63 @@ https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94 ```python title="hash_map.py" # 해시 테이블 순회 -# 키-값 쌍 key->value 순회 +# 키-값 쌍 key->value를 순회한다 for key, value in hmap.items(): print(key, "->", value) -# 키 key만 순회 + +# 키 key만 순회한다 for key in hmap.keys(): print(key) -# 값 value만 순회 -for value in hmap.values(): - print(value) + +# 값 value만 순회한다 +for val in hmap.values(): + print(val) ``` ```cpp title="hash_map.cpp" /* 해시 테이블 순회 */ -// 키-값 쌍 key->value 순회 -for (auto kv: map) { +// 키-값 쌍 key->value를 순회한다 +for (auto kv : map) { cout << kv.first << " -> " << kv.second << endl; } -// 이터레이터로 key->value 순회 + +// 반복자로 key->value를 순회한다 for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; + cout << iter->first << " -> " << iter->second << endl; } ``` ```java title="hash_map.java" /* 해시 테이블 순회 */ -// 키-값 쌍 key->value 순회 -for (Map.Entry kv: map.entrySet()) { +// 키-값 쌍 key->value를 순회한다 +for (Map.Entry kv : map.entrySet()) { System.out.println(kv.getKey() + " -> " + kv.getValue()); } -// 키 key만 순회 -for (int key: map.keySet()) { + +// 키 key만 순회한다 +for (int key : map.keySet()) { System.out.println(key); } -// 값 value만 순회 -for (String val: map.values()) { + +// 값 value만 순회한다 +for (String val : map.values()) { System.out.println(val); } ``` ```csharp title="hash_map.cs" /* 해시 테이블 순회 */ -// 키-값 쌍 Key->Value 순회 +// 키-값 쌍 key->value를 순회한다 foreach (var kv in map) { Console.WriteLine(kv.Key + " -> " + kv.Value); } -// 키 key만 순회 + +// 키 key만 순회한다 foreach (int key in map.Keys) { Console.WriteLine(key); } -// 값 value만 순회 + +// 값 value만 순회한다 foreach (string val in map.Values) { Console.WriteLine(val); } @@ -323,15 +327,17 @@ foreach (string val in map.Values) { ```go title="hash_map_test.go" /* 해시 테이블 순회 */ -// 키-값 쌍 key->value 순회 +// 키-값 쌍 key->value를 순회한다 for key, value := range hmap { fmt.Println(key, "->", value) } -// 키 key만 순회 + +// 키 key만 순회한다 for key := range hmap { fmt.Println(key) } -// 값 value만 순회 + +// 값 value만 순회한다 for _, value := range hmap { fmt.Println(value) } @@ -339,15 +345,17 @@ for _, value := range hmap { ```swift title="hash_map.swift" /* 해시 테이블 순회 */ -// 키-값 쌍 Key->Value 순회 +// 키-값 쌍 key->value를 순회한다 for (key, value) in map { print("\(key) -> \(value)") } -// 키 Key만 순회 + +// 키 key만 순회한다 for key in map.keys { print(key) } -// 값 Value만 순회 + +// 값 value만 순회한다 for value in map.values { print(value) } @@ -355,15 +363,17 @@ for value in map.values { ```javascript title="hash_map.js" /* 해시 테이블 순회 */ -console.info('\n키-값 쌍 Key->Value 순회'); +// 키-값 쌍 key->value를 순회한다 for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\n키 Key만 순회'); + +// 키 key만 순회한다 for (const k of map.keys()) { console.info(k); } -console.info('\n값 Value만 순회'); + +// 값 value만 순회한다 for (const v of map.values()) { console.info(v); } @@ -371,15 +381,17 @@ for (const v of map.values()) { ```typescript title="hash_map.ts" /* 해시 테이블 순회 */ -console.info('\n키-값 쌍 Key->Value 순회'); +// 키-값 쌍 key->value를 순회한다 for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\n키 Key만 순회'); + +// 키 key만 순회한다 for (const k of map.keys()) { console.info(k); } -console.info('\n값 Value만 순회'); + +// 값 value만 순회한다 for (const v of map.values()) { console.info(v); } @@ -387,35 +399,29 @@ for (const v of map.values()) { ```dart title="hash_map.dart" /* 해시 테이블 순회 */ -// 키-값 쌍 Key->Value 순회 -map.forEach((key, value) { - print('$key -> $value'); -}); +// 키-값 쌍 key->value를 순회한다 +map.forEach((key, value) => print("$key -> $value")); -// 키 Key만 순회 -map.keys.forEach((key) { - print(key); -}); +// 키 key만 순회한다 +map.keys.forEach((key) => print(key)); -// 값 Value만 순회 -map.values.forEach((value) { - print(value); -}); +// 값 value만 순회한다 +map.values.forEach((value) => print(value)); ``` ```rust title="hash_map.rs" -/* 해시 테이블 순회 */ -// 키-값 쌍 Key->Value 순회 +// 해시 테이블 순회 +// 키-값 쌍 key->value를 순회한다 for (key, value) in &map { println!("{key} -> {value}"); } -// 키 Key만 순회 +// 키 key만 순회한다 for key in map.keys() { println!("{key}"); } -// 값 Value만 순회 +// 값 value만 순회한다 for value in map.values() { println!("{value}"); } @@ -427,15 +433,17 @@ for value in map.values() { ```kotlin title="hash_map.kt" /* 해시 테이블 순회 */ -// 키-값 쌍 key->value 순회 +// 키-값 쌍 key->value를 순회한다 for ((key, value) in map) { println("$key -> $value") } -// 키 key만 순회 + +// 키 key만 순회한다 for (key in map.keys) { println(key) } -// 값 value만 순회 + +// 값 value만 순회한다 for (_val in map.values) { println(_val) } @@ -443,15 +451,15 @@ for (_val in map.values) { ```ruby title="hash_map.rb" # 해시 테이블 순회 -# 키-값 쌍 key->value 순회 +# 키-값 쌍 key->value를 순회한다 hmap.entries.each { |key, value| puts "#{key} -> #{value}" } -# 키 key만 순회 +# 키 key만 순회한다 hmap.keys.each { |key| puts key } -# 값 value만 순회 +# 값 value만 순회한다 hmap.values.each { |val| puts val } ``` -https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%B6%94%EA%B0%80%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20%28key%2C%20value%29%20%EC%B6%94%EA%B0%80%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20%23%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20key-%3Evalue%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%ED%82%A4%20key%EB%A7%8C%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%EA%B0%92%20value%EB%A7%8C%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%EC%B6%94%EA%B0%80%20%EC%97%B0%EC%82%B0%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%EC%97%90%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20%28key%2C%20value%29%20%EC%B6%94%EA%B0%80%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%95%B4%EC%8B%9C%20%ED%85%8C%EC%9D%B4%EB%B8%94%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20%23%20%ED%82%A4-%EA%B0%92%20%EC%8C%8D%20key-%3Evalue%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%ED%82%A4%20key%EB%A7%8C%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%EA%B0%92%20value%EB%A7%8C%20%EC%88%9C%ED%9A%8C%0A%20%20%20%20for%20val%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28val%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_heap/heap.md b/ko/codes/snippets/chapter_heap/heap.md index 74a50ad81..48b45ca12 100644 --- a/ko/codes/snippets/chapter_heap/heap.md +++ b/ko/codes/snippets/chapter_heap/heap.md @@ -6,8 +6,8 @@ min_heap, flag = [], 1 max_heap, flag = [], -1 # Python의 heapq 모듈은 기본적으로 최소 힙을 구현한다 -# 원소의 부호를 바꾼 뒤 삽입하면 대소 관계가 뒤집히므로 최대 힙을 구현할 수 있다 -# 이 예제에서 flag = 1이면 최소 힙, flag = -1이면 최대 힙에 해당한다 +# 원소의 부호를 바꾸어 힙에 삽입하면 대소 관계가 뒤집히므로 최대 힙을 구현할 수 있다 +# 이 예제에서 flag = 1은 최소 힙에, flag = -1은 최대 힙에 해당한다 # 힙에 원소 삽입 heapq.heappush(max_heap, flag * 1) @@ -16,24 +16,25 @@ heapq.heappush(max_heap, flag * 2) heapq.heappush(max_heap, flag * 5) heapq.heappush(max_heap, flag * 4) -# 힙의 루트 원소 구하기 -peek: int = flag * max_heap[0] # 5 +# 힙의 루트 원소 반환 +peek: int = flag * max_heap[0] # 5 # 힙의 루트 원소 꺼내기 -# 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 -val = flag * heapq.heappop(max_heap) # 5 -val = flag * heapq.heappop(max_heap) # 4 -val = flag * heapq.heappop(max_heap) # 3 -val = flag * heapq.heappop(max_heap) # 2 -val = flag * heapq.heappop(max_heap) # 1 +# 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 -# 힙의 크기 구하기 +# 힙 크기 반환 size: int = len(max_heap) -# 힙이 비어 있는지 확인 +# 힙이 비어 있는지 판단 is_empty: bool = not max_heap -# 리스트를 입력받아 힙 구성 +# 리스트를 입력하여 힙 구성 +# 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) ``` @@ -52,24 +53,25 @@ maxHeap.push(2); maxHeap.push(5); maxHeap.push(4); -/* 힙의 루트 원소 구하기 */ +/* 힙의 루트 원소 반환 */ int peek = maxHeap.top(); // 5 /* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 +// 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 maxHeap.pop(); // 5 maxHeap.pop(); // 4 maxHeap.pop(); // 3 maxHeap.pop(); // 2 maxHeap.pop(); // 1 -/* 힙의 크기 구하기 */ +/* 힙 크기 반환 */ int size = maxHeap.size(); -/* 힙이 비어 있는지 확인 */ +/* 힙이 비어 있는지 판단 */ bool isEmpty = maxHeap.empty(); -/* 리스트를 입력받아 힙 구성 */ +/* 리스트를 입력하여 힙 구성 */ +// 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 vector input{1, 3, 2, 5, 4}; minHeap = priority_queue, greater>(input.begin(), input.end()); ``` @@ -88,24 +90,25 @@ maxHeap.offer(2); maxHeap.offer(5); maxHeap.offer(4); -/* 힙의 루트 원소 구하기 */ +/* 힙의 루트 원소 반환 */ int peek = maxHeap.peek(); // 5 /* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 +// 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 peek = maxHeap.poll(); // 5 peek = maxHeap.poll(); // 4 peek = maxHeap.poll(); // 3 peek = maxHeap.poll(); // 2 peek = maxHeap.poll(); // 1 -/* 힙의 크기 구하기 */ +/* 힙 크기 반환 */ int size = maxHeap.size(); -/* 힙이 비어 있는지 확인 */ +/* 힙이 비어 있는지 판단 */ boolean isEmpty = maxHeap.isEmpty(); -/* 리스트를 입력받아 힙 구성 */ +/* 리스트를 입력하여 힙 구성 */ +// 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); ``` @@ -113,7 +116,7 @@ minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); /* 힙 초기화 */ // 최소 힙 초기화 PriorityQueue minHeap = new(); -// 최대 힙 초기화(lambda 식으로 Comparer를 수정하면 된다) +// 최대 힙 초기화(람다 식으로 Comparer를 변경하면 된다) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); /* 힙에 원소 삽입 */ @@ -123,24 +126,25 @@ maxHeap.Enqueue(2, 2); maxHeap.Enqueue(5, 5); maxHeap.Enqueue(4, 4); -/* 힙의 루트 원소 구하기 */ -int peek = maxHeap.Peek();//5 +/* 힙의 루트 원소 반환 */ +int peek = maxHeap.Peek(); // 5 /* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +// 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 -/* 힙의 크기 구하기 */ +/* 힙 크기 반환 */ int size = maxHeap.Count; -/* 힙이 비어 있는지 확인 */ +/* 힙이 비어 있는지 판단 */ bool isEmpty = maxHeap.Count == 0; -/* 리스트를 입력받아 힙 구성 */ +/* 리스트를 입력하여 힙 구성 */ +// 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); ``` @@ -149,81 +153,83 @@ minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); // heap.Interface를 구현하려면 sort.Interface도 구현해야 한다 type intHeap []any -// Push는 heap.Interface의 메서드로, 힙에 원소를 삽입한다 +// Push: heap.Interface의 함수로, 힙에 원소를 삽입한다 func (h *intHeap) Push(x any) { // Push와 Pop은 포인터 리시버(pointer receiver)를 매개변수로 사용한다 - // 슬라이스의 내용뿐 아니라 길이도 수정하기 때문이다. + // 슬라이스의 내용뿐 아니라 길이도 변경하기 때문이다. *h = append(*h, x.(int)) } -// Pop은 heap.Interface의 메서드로, 힙의 루트 원소를 꺼낸다 +// Pop: heap.Interface의 함수로, 힙의 루트 원소를 꺼낸다 func (h *intHeap) Pop() any { - // 꺼낼 원소는 맨 끝에 저장되어 있다 + // 꺼낼 원소는 맨 마지막에 저장되어 있다 last := (*h)[len(*h)-1] *h = (*h)[:len(*h)-1] return last } -// Len은 sort.Interface의 메서드다 +// Len: sort.Interface의 함수 func (h *intHeap) Len() int { return len(*h) } -// Less는 sort.Interface의 메서드다 +// Less: sort.Interface의 함수 func (h *intHeap) Less(i, j int) bool { - // 최소 힙을 구현하려면 부등호를 <로 바꿔야 한다 + // 최소 힙을 구현하려면 부등호를 <로 바꾸어야 한다 return (*h)[i].(int) > (*h)[j].(int) } -// Swap은 sort.Interface의 메서드다 +// Swap: sort.Interface의 함수 func (h *intHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } -// Top은 힙의 루트 원소를 구한다 +// Top: 힙의 루트 원소를 반환한다 func (h *intHeap) Top() any { return (*h)[0] } -/* 실행 코드 */ func TestHeap(t *testing.T) { /* 힙 초기화 */ // 최대 힙 초기화 maxHeap := &intHeap{} heap.Init(maxHeap) /* 힙에 원소 삽입 */ - // heap.Interface의 메서드를 호출하여 원소를 추가한다 + // heap.Interface의 함수를 호출하여 원소를 추가한다 heap.Push(maxHeap, 1) heap.Push(maxHeap, 3) heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) - /* 힙의 루트 원소 구하기 */ + /* 힙의 루트 원소 반환 */ top := maxHeap.Top() fmt.Printf("힙의 루트 원소: %d\n", top) /* 힙의 루트 원소 꺼내기 */ - // heap.Interface의 메서드를 호출하여 원소를 제거한다 - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 + // heap.Interface의 함수를 호출하여 원소를 제거한다 + fmt.Printf("힙에서 꺼낸 원소: %d\n", heap.Pop(maxHeap)) // 5 + fmt.Printf("힙에서 꺼낸 원소: %d\n", heap.Pop(maxHeap)) // 4 + fmt.Printf("힙에서 꺼낸 원소: %d\n", heap.Pop(maxHeap)) // 3 + fmt.Printf("힙에서 꺼낸 원소: %d\n", heap.Pop(maxHeap)) // 2 + fmt.Printf("힙에서 꺼낸 원소: %d\n", heap.Pop(maxHeap)) // 1 - /* 힙의 크기 구하기 */ + /* 힙 크기 반환 */ size := len(*maxHeap) - fmt.Printf("힙의 원소 수: %d\n", size) + fmt.Printf("힙의 원소 개수: %d\n", size) - /* 힙이 비어 있는지 확인 */ + /* 힙이 비어 있는지 판단 */ isEmpty := len(*maxHeap) == 0 fmt.Printf("힙이 비어 있는가: %t\n", isEmpty) } ``` ```swift title="heap.swift" +import HeapModule + /* 힙 초기화 */ -// Swift의 Heap 타입은 최대 힙과 최소 힙을 모두 지원하며, swift-collections를 가져와야 한다 +// Swift의 Heap 타입은 최대 힙과 최소 힙을 모두 지원하며, swift-collections 패키지를 도입해야 한다 var heap = Heap() /* 힙에 원소 삽입 */ @@ -233,8 +239,8 @@ heap.insert(2) heap.insert(5) heap.insert(4) -/* 힙의 루트 원소 구하기 */ -var peek = heap.max()! +/* 힙의 루트 원소 반환 */ +var peek = heap.max() /* 힙의 루트 원소 꺼내기 */ peek = heap.removeMax() // 5 @@ -243,13 +249,14 @@ peek = heap.removeMax() // 3 peek = heap.removeMax() // 2 peek = heap.removeMax() // 1 -/* 힙의 크기 구하기 */ +/* 힙 크기 반환 */ let size = heap.count -/* 힙이 비어 있는지 확인 */ +/* 힙이 비어 있는지 판단 */ let isEmpty = heap.isEmpty -/* 리스트를 입력받아 힙 구성 */ +/* 리스트를 입력하여 힙 구성 */ +// 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 let heap2 = Heap([1, 3, 2, 5, 4]) ``` @@ -266,12 +273,13 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +use std::{cmp::Reverse, collections::BinaryHeap}; /* 힙 초기화 */ // 최소 힙 초기화 -let mut min_heap = BinaryHeap::>::new(); +// Rust의 BinaryHeap은 최대 힙이며, 최소 힙을 만들려면 원소를 Reverse로 감싸야 한다 +#[allow(unused_assignments)] +let mut min_heap = BinaryHeap::new(); // 최대 힙 초기화 let mut max_heap = BinaryHeap::new(); @@ -282,25 +290,26 @@ max_heap.push(2); max_heap.push(5); max_heap.push(4); -/* 힙의 루트 원소 구하기 */ -let peek = max_heap.peek().unwrap(); // 5 +/* 힙의 루트 원소 반환 */ +let peek = max_heap.peek().unwrap(); // 5 /* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 -let peek = max_heap.pop().unwrap(); // 5 -let peek = max_heap.pop().unwrap(); // 4 -let peek = max_heap.pop().unwrap(); // 3 -let peek = max_heap.pop().unwrap(); // 2 -let peek = max_heap.pop().unwrap(); // 1 +// 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 -/* 힙의 크기 구하기 */ +/* 힙 크기 반환 */ let size = max_heap.len(); -/* 힙이 비어 있는지 확인 */ +/* 힙이 비어 있는지 판단 */ let is_empty = max_heap.is_empty(); -/* 리스트를 입력받아 힙 구성 */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +/* 리스트를 입력하여 힙 구성 */ +// 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 +min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); ``` ```c title="heap.c" @@ -321,25 +330,26 @@ maxHeap.offer(2) maxHeap.offer(5) maxHeap.offer(4) -/* 힙의 루트 원소 구하기 */ +/* 힙의 루트 원소 반환 */ var peek = maxHeap.peek() // 5 /* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 +// 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 peek = maxHeap.poll() // 5 peek = maxHeap.poll() // 4 peek = maxHeap.poll() // 3 peek = maxHeap.poll() // 2 peek = maxHeap.poll() // 1 -/* 힙의 크기 구하기 */ +/* 힙 크기 반환 */ val size = maxHeap.size -/* 힙이 비어 있는지 확인 */ +/* 힙이 비어 있는지 판단 */ val isEmpty = maxHeap.isEmpty() -/* 리스트를 입력받아 힙 구성 */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +/* 리스트를 입력하여 힙 구성 */ +// 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` ```ruby title="heap.rb" @@ -347,4 +357,4 @@ minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` -https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%EC%9D%98%20heapq%20%EB%AA%A8%EB%93%88%EC%9D%80%20%EA%B8%B0%EB%B3%B8%EC%A0%81%EC%9C%BC%EB%A1%9C%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%EC%9D%84%20%EA%B5%AC%ED%98%84%ED%95%9C%EB%8B%A4%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%EC%9D%98%20%EB%B6%80%ED%98%B8%EB%A5%BC%20%EB%B0%94%EA%BE%BC%20%EB%92%A4%20%EC%82%BD%EC%9E%85%ED%95%98%EB%A9%B4%20%EB%8C%80%EC%86%8C%20%EA%B4%80%EA%B3%84%EA%B0%80%20%EB%92%A4%EC%A7%91%ED%9E%88%EB%AF%80%EB%A1%9C%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%EC%9D%84%20%EA%B5%AC%ED%98%84%ED%95%A0%20%EC%88%98%20%EC%9E%88%EB%8B%A4%0A%20%20%20%20%23%20%EC%9D%B4%20%EC%98%88%EC%A0%9C%EC%97%90%EC%84%9C%20flag%20%3D%201%EC%9D%B4%EB%A9%B4%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%2C%20flag%20%3D%20-1%EC%9D%B4%EB%A9%B4%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%EC%97%90%20%ED%95%B4%EB%8B%B9%ED%95%9C%EB%8B%A4%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%EB%A3%A8%ED%8A%B8%20%EC%9B%90%EC%86%8C%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%EB%A3%A8%ED%8A%B8%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20%23%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%EB%93%A4%EC%9D%80%20%ED%81%B0%20%EA%B0%92%EB%B6%80%ED%84%B0%20%EC%9E%91%EC%9D%80%20%EA%B0%92%20%EC%88%9C%EC%84%9C%EB%A1%9C%20%EB%82%98%EC%97%B4%EB%90%9C%EB%8B%A4%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%ED%81%AC%EA%B8%B0%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A5%BC%20%EC%9E%85%EB%A0%A5%EB%B0%9B%EC%95%84%20%ED%9E%99%20%EA%B5%AC%EC%84%B1%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%EC%9D%98%20heapq%20%EB%AA%A8%EB%93%88%EC%9D%80%20%EA%B8%B0%EB%B3%B8%EC%A0%81%EC%9C%BC%EB%A1%9C%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%EC%9D%84%20%EA%B5%AC%ED%98%84%ED%95%9C%EB%8B%A4%0A%20%20%20%20%23%20%EC%9B%90%EC%86%8C%EC%9D%98%20%EB%B6%80%ED%98%B8%EB%A5%BC%20%EB%B0%94%EA%BE%BC%20%EB%92%A4%20%EC%82%BD%EC%9E%85%ED%95%98%EB%A9%B4%20%EB%8C%80%EC%86%8C%20%EA%B4%80%EA%B3%84%EA%B0%80%20%EB%92%A4%EC%A7%91%ED%9E%88%EB%AF%80%EB%A1%9C%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%EC%9D%84%20%EA%B5%AC%ED%98%84%ED%95%A0%20%EC%88%98%20%EC%9E%88%EB%8B%A4%0A%20%20%20%20%23%20%EC%9D%B4%20%EC%98%88%EC%A0%9C%EC%97%90%EC%84%9C%20flag%20%3D%201%EC%9D%B4%EB%A9%B4%20%EC%B5%9C%EC%86%8C%20%ED%9E%99%2C%20flag%20%3D%20-1%EC%9D%B4%EB%A9%B4%20%EC%B5%9C%EB%8C%80%20%ED%9E%99%EC%97%90%20%ED%95%B4%EB%8B%B9%ED%95%9C%EB%8B%A4%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%97%90%20%EC%9B%90%EC%86%8C%20%EC%82%BD%EC%9E%85%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%EB%A3%A8%ED%8A%B8%20%EC%9B%90%EC%86%8C%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%EB%A3%A8%ED%8A%B8%20%EC%9B%90%EC%86%8C%20%EA%BA%BC%EB%82%B4%EA%B8%B0%0A%20%20%20%20%23%20%EA%BA%BC%EB%82%B8%20%EC%9B%90%EC%86%8C%EB%93%A4%EC%9D%80%20%ED%81%B0%20%EA%B0%92%EB%B6%80%ED%84%B0%20%EC%9E%91%EC%9D%80%20%EA%B0%92%20%EC%88%9C%EC%84%9C%EB%A1%9C%20%EB%82%98%EC%97%B4%EB%90%9C%EB%8B%A4%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%98%20%ED%81%AC%EA%B8%B0%20%EA%B5%AC%ED%95%98%EA%B8%B0%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%ED%9E%99%EC%9D%B4%20%EB%B9%84%EC%96%B4%20%EC%9E%88%EB%8A%94%EC%A7%80%20%ED%99%95%EC%9D%B8%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%EB%A6%AC%EC%8A%A4%ED%8A%B8%EB%A5%BC%20%EC%9E%85%EB%A0%A5%EB%B0%9B%EC%95%84%20%ED%9E%99%20%EA%B5%AC%EC%84%B1%0A%20%20%20%20%23%20%EC%8B%9C%EA%B0%84%20%EB%B3%B5%EC%9E%A1%EB%8F%84%EB%8A%94%20O%28n%29%EC%9D%B4%EB%A9%B0%20O%28nlogn%29%EC%9D%B4%20%EC%95%84%EB%8B%88%EB%8B%A4%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/snippets/chapter_stack_and_queue/deque.md b/ko/codes/snippets/chapter_stack_and_queue/deque.md index 465f2364c..969732890 100644 --- a/ko/codes/snippets/chapter_stack_and_queue/deque.md +++ b/ko/codes/snippets/chapter_stack_and_queue/deque.md @@ -5,25 +5,25 @@ from collections import deque # 덱 초기화 deq: deque[int] = deque() -# 덱에 원소 삽입 -deq.append(2) # 맨 뒤에 추가 +# 원소 삽입 +deq.append(2) # 맨 뒤에 추가한다 deq.append(5) deq.append(4) -deq.appendleft(3) # 맨 앞에 추가 +deq.appendleft(3) # 맨 앞에 추가한다 deq.appendleft(1) # 원소 접근 front: int = deq[0] # 맨 앞 원소 rear: int = deq[-1] # 맨 뒤 원소 -# 덱에서 원소 꺼내기 -pop_front: int = deq.popleft() # 맨 앞 원소 꺼내기 -pop_rear: int = deq.pop() # 맨 뒤 원소 꺼내기 +# 원소 꺼내기 +pop_front: int = deq.popleft() # 맨 앞 원소를 꺼낸다 +pop_rear: int = deq.pop() # 맨 뒤 원소를 꺼낸다 -# 덱 길이 구하기 +# 덱의 길이 반환 size: int = len(deq) -# 덱이 비어 있는지 확인 +# 덱이 비어 있는지 판단 is_empty: bool = len(deq) == 0 ``` @@ -31,25 +31,25 @@ is_empty: bool = len(deq) == 0 /* 덱 초기화 */ deque deque; -/* 덱에 원소 삽입 */ -deque.push_back(2); // 맨 뒤에 추가 +/* 원소 삽입 */ +deque.push_back(2); // 맨 뒤에 추가한다 deque.push_back(5); deque.push_back(4); -deque.push_front(3); // 맨 앞에 추가 +deque.push_front(3); // 맨 앞에 추가한다 deque.push_front(1); /* 원소 접근 */ int front = deque.front(); // 맨 앞 원소 -int back = deque.back(); // 맨 뒤 원소 +int back = deque.back(); // 맨 뒤 원소 -/* 덱에서 원소 꺼내기 */ -deque.pop_front(); // 맨 앞 원소 꺼내기 -deque.pop_back(); // 맨 뒤 원소 꺼내기 +/* 원소 꺼내기 */ +deque.pop_front(); // 맨 앞 원소를 꺼낸다 +deque.pop_back(); // 맨 뒤 원소를 꺼낸다 -/* 덱 길이 구하기 */ +/* 덱의 길이 반환 */ int size = deque.size(); -/* 덱이 비어 있는지 확인 */ +/* 덱이 비어 있는지 판단 */ bool empty = deque.empty(); ``` @@ -57,25 +57,25 @@ bool empty = deque.empty(); /* 덱 초기화 */ Deque deque = new LinkedList<>(); -/* 덱에 원소 삽입 */ -deque.offerLast(2); // 맨 뒤에 추가 +/* 원소 삽입 */ +deque.offerLast(2); // 맨 뒤에 추가한다 deque.offerLast(5); deque.offerLast(4); -deque.offerFirst(3); // 맨 앞에 추가 +deque.offerFirst(3); // 맨 앞에 추가한다 deque.offerFirst(1); /* 원소 접근 */ -int peekFirst = deque.peekFirst(); // 맨 앞 원소 -int peekLast = deque.peekLast(); // 맨 뒤 원소 +int peekFirst = deque.peekFirst(); // 맨 앞 원소 +int peekLast = deque.peekLast(); // 맨 뒤 원소 -/* 덱에서 원소 꺼내기 */ -int popFirst = deque.pollFirst(); // 맨 앞 원소 꺼내기 -int popLast = deque.pollLast(); // 맨 뒤 원소 꺼내기 +/* 원소 꺼내기 */ +int popFirst = deque.pollFirst(); // 맨 앞 원소를 꺼낸다 +int popLast = deque.pollLast(); // 맨 뒤 원소를 꺼낸다 -/* 덱 길이 구하기 */ +/* 덱의 길이 반환 */ int size = deque.size(); -/* 덱이 비어 있는지 확인 */ +/* 덱이 비어 있는지 판단 */ boolean isEmpty = deque.isEmpty(); ``` @@ -84,25 +84,25 @@ boolean isEmpty = deque.isEmpty(); // C#에서는 연결 리스트 LinkedList를 덱으로 사용한다 LinkedList deque = new(); -/* 덱에 원소 삽입 */ -deque.AddLast(2); // 맨 뒤에 추가 +/* 원소 삽입 */ +deque.AddLast(2); // 맨 뒤에 추가한다 deque.AddLast(5); deque.AddLast(4); -deque.AddFirst(3); // 맨 앞에 추가 +deque.AddFirst(3); // 맨 앞에 추가한다 deque.AddFirst(1); /* 원소 접근 */ -int peekFirst = deque.First.Value; // 맨 앞 원소 -int peekLast = deque.Last.Value; // 맨 뒤 원소 +int? peekFirst = deque.First?.Value; // 맨 앞 원소 +int? peekLast = deque.Last?.Value; // 맨 뒤 원소 -/* 덱에서 원소 꺼내기 */ -deque.RemoveFirst(); // 맨 앞 원소 꺼내기 -deque.RemoveLast(); // 맨 뒤 원소 꺼내기 +/* 원소 꺼내기 */ +deque.RemoveFirst(); // 맨 앞 원소를 꺼낸다 +deque.RemoveLast(); // 맨 뒤 원소를 꺼낸다 -/* 덱 길이 구하기 */ +/* 덱의 길이 반환 */ int size = deque.Count; -/* 덱이 비어 있는지 확인 */ +/* 덱이 비어 있는지 판단 */ bool isEmpty = deque.Count == 0; ``` @@ -111,25 +111,25 @@ bool isEmpty = deque.Count == 0; // Go에서는 list를 덱으로 사용한다 deque := list.New() -/* 덱에 원소 삽입 */ -deque.PushBack(2) // 맨 뒤에 추가 +/* 원소 삽입 */ +deque.PushBack(2) // 맨 뒤에 추가한다 deque.PushBack(5) deque.PushBack(4) -deque.PushFront(3) // 맨 앞에 추가 +deque.PushFront(3) // 맨 앞에 추가한다 deque.PushFront(1) /* 원소 접근 */ front := deque.Front() // 맨 앞 원소 -rear := deque.Back() // 맨 뒤 원소 +rear := deque.Back() // 맨 뒤 원소 -/* 덱에서 원소 꺼내기 */ -deque.Remove(front) // 맨 앞 원소 꺼내기 -deque.Remove(rear) // 맨 뒤 원소 꺼내기 +/* 원소 꺼내기 */ +deque.Remove(front) // 맨 앞 원소를 꺼낸다 +deque.Remove(rear) // 맨 뒤 원소를 꺼낸다 -/* 덱 길이 구하기 */ +/* 덱의 길이 반환 */ size := deque.Len() -/* 덱이 비어 있는지 확인 */ +/* 덱이 비어 있는지 판단 */ isEmpty := deque.Len() == 0 ``` @@ -138,39 +138,39 @@ isEmpty := deque.Len() == 0 // Swift에는 내장 덱 클래스가 없으므로 Array를 덱으로 사용할 수 있다 var deque: [Int] = [] -/* 덱에 원소 삽입 */ -deque.append(2) // 맨 뒤에 추가 +/* 원소 삽입 */ +deque.append(2) // 맨 뒤에 추가한다 deque.append(5) deque.append(4) -deque.insert(3, at: 0) // 맨 앞에 추가 +deque.insert(3, at: 0) // 맨 앞에 추가한다 deque.insert(1, at: 0) /* 원소 접근 */ let peekFirst = deque.first! // 맨 앞 원소 let peekLast = deque.last! // 맨 뒤 원소 -/* 덱에서 원소 꺼내기 */ -// Array로 구현하면 popFirst의 복잡도는 O(n)이다 -let popFirst = deque.removeFirst() // 맨 앞 원소 꺼내기 -let popLast = deque.removeLast() // 맨 뒤 원소 꺼내기 +/* 원소 꺼내기 */ +// Array로 구현할 때 removeFirst의 복잡도는 O(n)이다 +let popFirst = deque.removeFirst() // 맨 앞 원소를 꺼낸다 +let popLast = deque.removeLast() // 맨 뒤 원소를 꺼낸다 -/* 덱 길이 구하기 */ +/* 덱의 길이 반환 */ let size = deque.count -/* 덱이 비어 있는지 확인 */ +/* 덱이 비어 있는지 판단 */ let isEmpty = deque.isEmpty ``` ```javascript title="deque.js" /* 덱 초기화 */ -// JavaScript에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 +// JavaScript에는 내장 덱이 없으므로 Array를 덱으로 사용한다 const deque = []; -/* 덱에 원소 삽입 */ +/* 원소 삽입 */ deque.push(2); deque.push(5); deque.push(4); -// 배열이므로 unshift() 메서드의 시간 복잡도는 O(n)임에 주의 +// 배열이므로 unshift() 메서드의 시간 복잡도는 O(n)임에 유의한다 deque.unshift(3); deque.unshift(1); @@ -178,28 +178,28 @@ deque.unshift(1); const peekFirst = deque[0]; const peekLast = deque[deque.length - 1]; -/* 덱에서 원소 꺼내기 */ -// 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 주의 +/* 원소 꺼내기 */ +// 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 유의한다 const popFront = deque.shift(); const popBack = deque.pop(); -/* 덱 길이 구하기 */ +/* 덱의 길이 반환 */ const size = deque.length; -/* 덱이 비어 있는지 확인 */ +/* 덱이 비어 있는지 판단 */ const isEmpty = size === 0; ``` ```typescript title="deque.ts" /* 덱 초기화 */ -// TypeScript에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 +// TypeScript에는 내장 덱이 없으므로 Array를 덱으로 사용한다 const deque: number[] = []; -/* 덱에 원소 삽입 */ +/* 원소 삽입 */ deque.push(2); deque.push(5); deque.push(4); -// 배열이므로 unshift() 메서드의 시간 복잡도는 O(n)임에 주의 +// 배열이므로 unshift() 메서드의 시간 복잡도는 O(n)임에 유의한다 deque.unshift(3); deque.unshift(1); @@ -207,72 +207,68 @@ deque.unshift(1); const peekFirst: number = deque[0]; const peekLast: number = deque[deque.length - 1]; -/* 덱에서 원소 꺼내기 */ -// 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 주의 +/* 원소 꺼내기 */ +// 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 유의한다 const popFront: number = deque.shift() as number; const popBack: number = deque.pop() as number; -/* 덱 길이 구하기 */ +/* 덱의 길이 반환 */ const size: number = deque.length; -/* 덱이 비어 있는지 확인 */ +/* 덱이 비어 있는지 판단 */ const isEmpty: boolean = size === 0; ``` ```dart title="deque.dart" /* 덱 초기화 */ -// Dart의 Queue는 덱으로 정의되어 있다 -Queue deque = Queue(); +// Dart에서는 Queue가 덱으로 정의되어 있다 +final Queue deque = Queue(); -/* 덱에 원소 삽입 */ -deque.addLast(2); // 맨 뒤에 추가 +/* 원소 삽입 */ +deque.addLast(2); // 맨 뒤에 추가한다 deque.addLast(5); deque.addLast(4); -deque.addFirst(3); // 맨 앞에 추가 +deque.addFirst(3); // 맨 앞에 추가한다 deque.addFirst(1); /* 원소 접근 */ -int peekFirst = deque.first; // 맨 앞 원소 -int peekLast = deque.last; // 맨 뒤 원소 +final int peekFirst = deque.first; // 맨 앞 원소 +final int peekLast = deque.last; // 맨 뒤 원소 -/* 덱에서 원소 꺼내기 */ -int popFirst = deque.removeFirst(); // 맨 앞 원소 꺼내기 -int popLast = deque.removeLast(); // 맨 뒤 원소 꺼내기 +/* 원소 꺼내기 */ +final int popFirst = deque.removeFirst(); // 맨 앞 원소를 꺼낸다 +final int popLast = deque.removeLast(); // 맨 뒤 원소를 꺼낸다 -/* 덱 길이 구하기 */ -int size = deque.length; +/* 덱의 길이 반환 */ +final int size = deque.length; -/* 덱이 비어 있는지 확인 */ -bool isEmpty = deque.isEmpty; +/* 덱이 비어 있는지 판단 */ +final bool isEmpty = deque.isEmpty; ``` ```rust title="deque.rs" -/* 덱 초기화 */ -let mut deque: VecDeque = VecDeque::new(); +// 덱 초기화 +let mut deque: VecDeque = VecDeque::new(); -/* 덱에 원소 삽입 */ -deque.push_back(2); // 맨 뒤에 추가 +/* 원소 삽입 */ +deque.push_back(2); // 맨 뒤에 추가한다 deque.push_back(5); deque.push_back(4); -deque.push_front(3); // 맨 앞에 추가 +deque.push_front(3); // 맨 앞에 추가한다 deque.push_front(1); -/* 원소 접근 */ -if let Some(front) = deque.front() { // 맨 앞 원소 -} -if let Some(rear) = deque.back() { // 맨 뒤 원소 -} +// 원소 접근 +let peek_first = deque.front().unwrap(); // 맨 앞 원소 +let peek_last = deque.back().unwrap(); // 맨 뒤 원소 -/* 덱에서 원소 꺼내기 */ -if let Some(pop_front) = deque.pop_front() { // 맨 앞 원소 꺼내기 -} -if let Some(pop_rear) = deque.pop_back() { // 맨 뒤 원소 꺼내기 -} +// 원소 꺼내기 +let pop_first = deque.pop_front().unwrap(); // 맨 앞 원소를 꺼낸다 +let pop_last = deque.pop_back().unwrap(); // 맨 뒤 원소를 꺼낸다 -/* 덱 길이 구하기 */ +// 덱의 길이 반환 let size = deque.len(); -/* 덱이 비어 있는지 확인 */ +// 덱이 비어 있는지 판단 let is_empty = deque.is_empty(); ``` @@ -284,25 +280,25 @@ let is_empty = deque.is_empty(); /* 덱 초기화 */ val deque = LinkedList() -/* 덱에 원소 삽입 */ -deque.offerLast(2) // 맨 뒤에 추가 +/* 원소 삽입 */ +deque.offerLast(2) // 맨 뒤에 추가한다 deque.offerLast(5) deque.offerLast(4) -deque.offerFirst(3) // 맨 앞에 추가 +deque.offerFirst(3) // 맨 앞에 추가한다 deque.offerFirst(1) /* 원소 접근 */ val peekFirst = deque.peekFirst() // 맨 앞 원소 -val peekLast = deque.peekLast() // 맨 뒤 원소 +val peekLast = deque.peekLast() // 맨 뒤 원소 -/* 덱에서 원소 꺼내기 */ -val popFirst = deque.pollFirst() // 맨 앞 원소 꺼내기 -val popLast = deque.pollLast() // 맨 뒤 원소 꺼내기 +/* 원소 꺼내기 */ +val popFirst = deque.pollFirst() // 맨 앞 원소를 꺼낸다 +val popLast = deque.pollLast() // 맨 뒤 원소를 꺼낸다 -/* 덱 길이 구하기 */ +/* 덱의 길이 반환 */ val size = deque.size -/* 덱이 비어 있는지 확인 */ +/* 덱이 비어 있는지 판단 */ val isEmpty = deque.isEmpty() ``` @@ -311,11 +307,11 @@ val isEmpty = deque.isEmpty() # Ruby에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 deque = [] -# 덱에 원소 삽입 +# 원소 삽입 deque << 2 deque << 5 deque << 4 -# 배열이므로 Array#unshift 메서드의 시간 복잡도는 O(n)임에 주의 +# 배열이므로 Array#unshift 메서드의 시간 복잡도는 O(n)임에 유의한다 deque.unshift(3) deque.unshift(1) @@ -323,15 +319,15 @@ deque.unshift(1) peek_first = deque.first peek_last = deque.last -# 덱에서 원소 꺼내기 -# 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 주의 +# 원소 꺼내기 +# 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 유의한다 pop_front = deque.shift pop_back = deque.pop -# 덱 길이 구하기 +# 덱의 길이 반환 size = deque.length -# 덱이 비어 있는지 확인 +# 덱이 비어 있는지 판단 is_empty = size.zero? ``` diff --git a/ko/codes/snippets/chapter_stack_and_queue/queue.md b/ko/codes/snippets/chapter_stack_and_queue/queue.md index 1c7c87436..e799b1e1c 100644 --- a/ko/codes/snippets/chapter_stack_and_queue/queue.md +++ b/ko/codes/snippets/chapter_stack_and_queue/queue.md @@ -3,27 +3,27 @@ from collections import deque # 큐 초기화 -# Python에서는 보통 덱 클래스 deque를 큐로 사용한다 -# queue.Queue()는 전용 큐 클래스이지만 사용이 불편하므로 권하지 않는다 +# Python에서는 일반적으로 덱 클래스 deque를 큐로 사용한다 +# queue.Queue()는 전용 큐 클래스이지만 사용하기가 그다지 편리하지 않아 권장하지 않는다 que: deque[int] = deque() -# 큐에 원소 삽입 +# 원소 삽입 que.append(1) que.append(3) que.append(2) que.append(5) que.append(4) -# 큐의 맨 앞 원소에 접근 +# 맨 앞 원소 접근 front: int = que[0] -# 큐에서 원소 꺼내기 +# 원소 꺼내기 pop: int = que.popleft() -# 큐 길이 구하기 +# 큐의 길이 반환 size: int = len(que) -# 큐가 비어 있는지 확인 +# 큐가 비어 있는지 판단 is_empty: bool = len(que) == 0 ``` @@ -31,23 +31,23 @@ is_empty: bool = len(que) == 0 /* 큐 초기화 */ queue queue; -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); queue.push(5); queue.push(4); -/* 큐의 맨 앞 원소에 접근 */ +/* 맨 앞 원소 접근 */ int front = queue.front(); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ queue.pop(); -/* 큐 길이 구하기 */ +/* 큐의 길이 반환 */ int size = queue.size(); -/* 큐가 비어 있는지 확인 */ +/* 큐가 비어 있는지 판단 */ bool empty = queue.empty(); ``` @@ -55,23 +55,23 @@ bool empty = queue.empty(); /* 큐 초기화 */ Queue queue = new LinkedList<>(); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.offer(1); queue.offer(3); queue.offer(2); queue.offer(5); queue.offer(4); -/* 큐의 맨 앞 원소에 접근 */ +/* 맨 앞 원소 접근 */ int peek = queue.peek(); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ int pop = queue.poll(); -/* 큐 길이 구하기 */ +/* 큐의 길이 반환 */ int size = queue.size(); -/* 큐가 비어 있는지 확인 */ +/* 큐가 비어 있는지 판단 */ boolean isEmpty = queue.isEmpty(); ``` @@ -79,23 +79,23 @@ boolean isEmpty = queue.isEmpty(); /* 큐 초기화 */ Queue queue = new(); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.Enqueue(1); queue.Enqueue(3); queue.Enqueue(2); queue.Enqueue(5); queue.Enqueue(4); -/* 큐의 맨 앞 원소에 접근 */ +/* 맨 앞 원소 접근 */ int peek = queue.Peek(); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ int pop = queue.Dequeue(); -/* 큐 길이 구하기 */ +/* 큐의 길이 반환 */ int size = queue.Count; -/* 큐가 비어 있는지 확인 */ +/* 큐가 비어 있는지 판단 */ bool isEmpty = queue.Count == 0; ``` @@ -104,24 +104,24 @@ bool isEmpty = queue.Count == 0; // Go에서는 list를 큐로 사용한다 queue := list.New() -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.PushBack(1) queue.PushBack(3) queue.PushBack(2) queue.PushBack(5) queue.PushBack(4) -/* 큐의 맨 앞 원소에 접근 */ +/* 맨 앞 원소 접근 */ peek := queue.Front() -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ pop := queue.Front() queue.Remove(pop) -/* 큐 길이 구하기 */ +/* 큐의 길이 반환 */ size := queue.Len() -/* 큐가 비어 있는지 확인 */ +/* 큐가 비어 있는지 판단 */ isEmpty := queue.Len() == 0 ``` @@ -130,24 +130,24 @@ isEmpty := queue.Len() == 0 // Swift에는 내장 큐 클래스가 없으므로 Array를 큐로 사용할 수 있다 var queue: [Int] = [] -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.append(1) queue.append(3) queue.append(2) queue.append(5) queue.append(4) -/* 큐의 맨 앞 원소에 접근 */ +/* 맨 앞 원소 접근 */ let peek = queue.first! -/* 큐에서 원소 꺼내기 */ -// 배열이므로 removeFirst의 복잡도는 O(n)이다 +/* 원소 꺼내기 */ +// Array로 구현할 때 removeFirst의 복잡도는 O(n)이다 let pop = queue.removeFirst() -/* 큐 길이 구하기 */ +/* 큐의 길이 반환 */ let size = queue.count -/* 큐가 비어 있는지 확인 */ +/* 큐가 비어 있는지 판단 */ let isEmpty = queue.isEmpty ``` @@ -156,25 +156,25 @@ let isEmpty = queue.isEmpty // JavaScript에는 내장 큐가 없으므로 Array를 큐로 사용할 수 있다 const queue = []; -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); queue.push(5); queue.push(4); -/* 큐의 맨 앞 원소에 접근 */ +/* 맨 앞 원소 접근 */ const peek = queue[0]; -/* 큐에서 원소 꺼내기 */ -// 기반이 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 +/* 원소 꺼내기 */ +// 내부 자료 구조가 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 const pop = queue.shift(); -/* 큐 길이 구하기 */ +/* 큐의 길이 반환 */ const size = queue.length; -/* 큐가 비어 있는지 확인 */ -const empty = queue.length === 0; +/* 큐가 비어 있는지 판단 */ +const isEmpty = queue.length === 0; ``` ```typescript title="queue.ts" @@ -182,77 +182,75 @@ const empty = queue.length === 0; // TypeScript에는 내장 큐가 없으므로 Array를 큐로 사용할 수 있다 const queue: number[] = []; -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); queue.push(5); queue.push(4); -/* 큐의 맨 앞 원소에 접근 */ +/* 맨 앞 원소 접근 */ const peek = queue[0]; -/* 큐에서 원소 꺼내기 */ -// 기반이 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 +/* 원소 꺼내기 */ +// 내부 자료 구조가 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 const pop = queue.shift(); -/* 큐 길이 구하기 */ +/* 큐의 길이 반환 */ const size = queue.length; -/* 큐가 비어 있는지 확인 */ -const empty = queue.length === 0; +/* 큐가 비어 있는지 판단 */ +const isEmpty = queue.length === 0; ``` ```dart title="queue.dart" /* 큐 초기화 */ -// Dart의 Queue 클래스는 덱이며 일반 큐로도 사용할 수 있다 -Queue queue = Queue(); +// Dart에서는 일반적으로 덱 클래스 Queue를 큐로 사용한다 +final Queue queue = Queue(); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.add(1); queue.add(3); queue.add(2); queue.add(5); queue.add(4); -/* 큐의 맨 앞 원소에 접근 */ -int peek = queue.first; +/* 맨 앞 원소 접근 */ +final int peek = queue.first; -/* 큐에서 원소 꺼내기 */ -int pop = queue.removeFirst(); +/* 원소 꺼내기 */ +final int pop = queue.removeFirst(); -/* 큐 길이 구하기 */ -int size = queue.length; +/* 큐의 길이 반환 */ +final int size = queue.length; -/* 큐가 비어 있는지 확인 */ -bool isEmpty = queue.isEmpty; +/* 큐가 비어 있는지 판단 */ +final bool isEmpty = queue.isEmpty; ``` ```rust title="queue.rs" -/* 덱 초기화 */ -// Rust에서는 덱을 일반 큐로 사용한다 -let mut deque: VecDeque = VecDeque::new(); +// 큐 초기화 +// Rust에서는 일반적으로 덱 VecDeque를 큐로 사용한다 +let mut queue: VecDeque = VecDeque::new(); -/* 큐에 원소 삽입 */ -deque.push_back(1); -deque.push_back(3); -deque.push_back(2); -deque.push_back(5); -deque.push_back(4); +// 원소 삽입 +queue.push_back(1); +queue.push_back(3); +queue.push_back(2); +queue.push_back(5); +queue.push_back(4); -/* 큐의 맨 앞 원소에 접근 */ -if let Some(front) = deque.front() { -} +// 맨 앞 원소 접근 +let peek = queue.front().unwrap(); -/* 큐에서 원소 꺼내기 */ -if let Some(pop) = deque.pop_front() { -} +// 원소 꺼내기 +let pop = queue.pop_front().unwrap(); -/* 큐 길이 구하기 */ -let size = deque.len(); +// 큐의 길이 반환 +let size = queue.len(); -/* 큐가 비어 있는지 확인 */ -let is_empty = deque.is_empty(); +// 큐가 비어 있는지 판단 +let is_empty = queue.is_empty(); ``` ```c title="queue.c" @@ -263,49 +261,49 @@ let is_empty = deque.is_empty(); /* 큐 초기화 */ val queue = LinkedList() -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.offer(1) queue.offer(3) queue.offer(2) queue.offer(5) queue.offer(4) -/* 큐의 맨 앞 원소에 접근 */ +/* 맨 앞 원소 접근 */ val peek = queue.peek() -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ val pop = queue.poll() -/* 큐 길이 구하기 */ +/* 큐의 길이 반환 */ val size = queue.size -/* 큐가 비어 있는지 확인 */ +/* 큐가 비어 있는지 판단 */ val isEmpty = queue.isEmpty() ``` ```ruby title="queue.rb" # 큐 초기화 -# Ruby의 내장 큐(Thread::Queue)에는 peek와 순회 메서드가 없으므로 Array를 큐로 사용할 수 있다 +# Ruby의 내장 큐(Thread::Queue)에는 peek 메서드와 순회 메서드가 없으므로 Array를 큐로 사용할 수 있다 queue = [] -# 큐에 원소 삽입 +# 원소 삽입 queue.push(1) queue.push(3) queue.push(2) queue.push(5) queue.push(4) -# 큐 원소에 접근 +# 큐 원소 접근 peek = queue.first -# 큐에서 원소 꺼내기 -# 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 주의 +# 원소 꺼내기 +# 배열이므로 Array#shift 메서드의 시간 복잡도는 O(n)임에 유의한다 pop = queue.shift -# 큐 길이 구하기 +# 큐의 길이 반환 size = queue.length -# 큐가 비어 있는지 확인 +# 큐가 비어 있는지 판단 is_empty = queue.empty? ``` diff --git a/ko/codes/snippets/chapter_stack_and_queue/stack.md b/ko/codes/snippets/chapter_stack_and_queue/stack.md index a8f6ce82d..daca09df5 100644 --- a/ko/codes/snippets/chapter_stack_and_queue/stack.md +++ b/ko/codes/snippets/chapter_stack_and_queue/stack.md @@ -11,16 +11,16 @@ stack.append(2) stack.append(5) stack.append(4) -# 스택 맨 위 원소에 접근 +# 스택 맨 위 원소 접근 peek: int = stack[-1] # 스택에서 원소 꺼내기 pop: int = stack.pop() -# 스택 길이 구하기 +# 스택의 길이 반환 size: int = len(stack) -# 비어 있는지 확인 +# 비어 있는지 판단 is_empty: bool = len(stack) == 0 ``` @@ -35,16 +35,16 @@ stack.push(2); stack.push(5); stack.push(4); -/* 스택 맨 위 원소에 접근 */ +/* 스택 맨 위 원소 접근 */ int top = stack.top(); /* 스택에서 원소 꺼내기 */ stack.pop(); // 반환값 없음 -/* 스택 길이 구하기 */ +/* 스택의 길이 반환 */ int size = stack.size(); -/* 비어 있는지 확인 */ +/* 비어 있는지 판단 */ bool empty = stack.empty(); ``` @@ -59,16 +59,16 @@ stack.push(2); stack.push(5); stack.push(4); -/* 스택 맨 위 원소에 접근 */ +/* 스택 맨 위 원소 접근 */ int peek = stack.peek(); /* 스택에서 원소 꺼내기 */ int pop = stack.pop(); -/* 스택 길이 구하기 */ +/* 스택의 길이 반환 */ int size = stack.size(); -/* 비어 있는지 확인 */ +/* 비어 있는지 판단 */ boolean isEmpty = stack.isEmpty(); ``` @@ -83,22 +83,22 @@ stack.Push(2); stack.Push(5); stack.Push(4); -/* 스택 맨 위 원소에 접근 */ +/* 스택 맨 위 원소 접근 */ int peek = stack.Peek(); /* 스택에서 원소 꺼내기 */ int pop = stack.Pop(); -/* 스택 길이 구하기 */ +/* 스택의 길이 반환 */ int size = stack.Count; -/* 비어 있는지 확인 */ +/* 비어 있는지 판단 */ bool isEmpty = stack.Count == 0; ``` ```go title="stack_test.go" /* 스택 초기화 */ -// Go에서는 Slice를 스택으로 사용하는 것을 권한다 +// Go에서는 Slice를 스택으로 사용하는 것을 권장한다 var stack []int /* 스택에 원소 삽입 */ @@ -108,17 +108,17 @@ stack = append(stack, 2) stack = append(stack, 5) stack = append(stack, 4) -/* 스택 맨 위 원소에 접근 */ +/* 스택 맨 위 원소 접근 */ peek := stack[len(stack)-1] /* 스택에서 원소 꺼내기 */ pop := stack[len(stack)-1] stack = stack[:len(stack)-1] -/* 스택 길이 구하기 */ +/* 스택의 길이 반환 */ size := len(stack) -/* 비어 있는지 확인 */ +/* 비어 있는지 판단 */ isEmpty := len(stack) == 0 ``` @@ -134,16 +134,16 @@ stack.append(2) stack.append(5) stack.append(4) -/* 스택 맨 위 원소에 접근 */ +/* 스택 맨 위 원소 접근 */ let peek = stack.last! /* 스택에서 원소 꺼내기 */ let pop = stack.removeLast() -/* 스택 길이 구하기 */ +/* 스택의 길이 반환 */ let size = stack.count -/* 비어 있는지 확인 */ +/* 비어 있는지 판단 */ let isEmpty = stack.isEmpty ``` @@ -159,17 +159,17 @@ stack.push(2); stack.push(5); stack.push(4); -/* 스택 맨 위 원소에 접근 */ -const peek = stack[stack.length-1]; +/* 스택 맨 위 원소 접근 */ +const peek = stack[stack.length - 1]; /* 스택에서 원소 꺼내기 */ const pop = stack.pop(); -/* 스택 길이 구하기 */ +/* 스택의 길이 반환 */ const size = stack.length; -/* 비어 있는지 확인 */ -const is_empty = stack.length === 0; +/* 비어 있는지 판단 */ +const isEmpty = stack.length === 0; ``` ```typescript title="stack.ts" @@ -184,23 +184,23 @@ stack.push(2); stack.push(5); stack.push(4); -/* 스택 맨 위 원소에 접근 */ +/* 스택 맨 위 원소 접근 */ const peek = stack[stack.length - 1]; /* 스택에서 원소 꺼내기 */ const pop = stack.pop(); -/* 스택 길이 구하기 */ +/* 스택의 길이 반환 */ const size = stack.length; -/* 비어 있는지 확인 */ -const is_empty = stack.length === 0; +/* 비어 있는지 판단 */ +const isEmpty = stack.length === 0; ``` ```dart title="stack.dart" /* 스택 초기화 */ // Dart에는 내장 스택 클래스가 없으므로 List를 스택으로 사용할 수 있다 -List stack = []; +final List stack = []; /* 스택에 원소 삽입 */ stack.add(1); @@ -209,41 +209,41 @@ stack.add(2); stack.add(5); stack.add(4); -/* 스택 맨 위 원소에 접근 */ -int peek = stack.last; +/* 스택 맨 위 원소 접근 */ +final int peek = stack.last; /* 스택에서 원소 꺼내기 */ -int pop = stack.removeLast(); +final int pop = stack.removeLast(); -/* 스택 길이 구하기 */ -int size = stack.length; +/* 스택의 길이 반환 */ +final int size = stack.length; -/* 비어 있는지 확인 */ -bool isEmpty = stack.isEmpty; +/* 비어 있는지 판단 */ +final bool isEmpty = stack.isEmpty; ``` ```rust title="stack.rs" -/* 스택 초기화 */ -// Vec를 스택으로 사용 +// 스택 초기화 +// Rust에서는 Vec를 스택으로 사용하는 것을 권장한다 let mut stack: Vec = Vec::new(); -/* 스택에 원소 삽입 */ +// 스택에 원소 삽입 stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* 스택 맨 위 원소에 접근 */ -let top = stack.last().unwrap(); +// 스택 맨 위 원소 접근 +let peek = stack.last().unwrap(); -/* 스택에서 원소 꺼내기 */ +// 스택에서 원소 꺼내기 let pop = stack.pop().unwrap(); -/* 스택 길이 구하기 */ +// 스택의 길이 반환 let size = stack.len(); -/* 비어 있는지 확인 */ +// 스택이 비어 있는지 판단 let is_empty = stack.is_empty(); ``` @@ -262,16 +262,16 @@ stack.push(2) stack.push(5) stack.push(4) -/* 스택 맨 위 원소에 접근 */ +/* 스택 맨 위 원소 접근 */ val peek = stack.peek() /* 스택에서 원소 꺼내기 */ val pop = stack.pop() -/* 스택 길이 구하기 */ +/* 스택의 길이 반환 */ val size = stack.size -/* 비어 있는지 확인 */ +/* 비어 있는지 판단 */ val isEmpty = stack.isEmpty() ``` @@ -287,16 +287,16 @@ stack << 2 stack << 5 stack << 4 -# 스택 맨 위 원소에 접근 +# 스택 맨 위 원소 접근 peek = stack.last # 스택에서 원소 꺼내기 pop = stack.pop -# 스택 길이 구하기 +# 스택의 길이 반환 size = stack.length -# 비어 있는지 확인 +# 비어 있는지 판단 is_empty = stack.empty? ``` diff --git a/ko/codes/snippets/chapter_tree/binary_tree.md b/ko/codes/snippets/chapter_tree/binary_tree.md index b43edb2f5..ace700437 100644 --- a/ko/codes/snippets/chapter_tree/binary_tree.md +++ b/ko/codes/snippets/chapter_tree/binary_tree.md @@ -133,7 +133,6 @@ impl TreeNode { /* 이진 트리 노드 구조체 */ typedef struct TreeNode { int val; // 노드 값 - int height; // 노드 높이 struct TreeNode *left; // 왼쪽 자식 노드 포인터 struct TreeNode *right; // 오른쪽 자식 노드 포인터 } TreeNode; @@ -144,7 +143,6 @@ TreeNode *newTreeNode(int val) { node = (TreeNode *)malloc(sizeof(TreeNode)); node->val = val; - node->height = 0; node->left = NULL; node->right = NULL; return node; @@ -181,7 +179,7 @@ n2 = TreeNode(val=2) n3 = TreeNode(val=3) n4 = TreeNode(val=4) n5 = TreeNode(val=5) -# 노드 사이의 참조(포인터) 연결 +# 노드 사이의 참조(포인터)를 설정한다 n1.left = n2 n1.right = n3 n2.left = n4 @@ -191,12 +189,12 @@ n2.right = n5 ```cpp title="binary_tree.cpp" /* 이진 트리 초기화 */ // 노드 초기화 -TreeNode* n1 = new TreeNode(1); -TreeNode* n2 = new TreeNode(2); -TreeNode* n3 = new TreeNode(3); -TreeNode* n4 = new TreeNode(4); -TreeNode* n5 = new TreeNode(5); -// 노드 사이의 참조(포인터) 연결 +TreeNode *n1 = new TreeNode(1); +TreeNode *n2 = new TreeNode(2); +TreeNode *n3 = new TreeNode(3); +TreeNode *n4 = new TreeNode(4); +TreeNode *n5 = new TreeNode(5); +// 노드 사이의 참조(포인터)를 설정한다 n1->left = n2; n1->right = n3; n2->left = n4; @@ -204,13 +202,14 @@ n2->right = n5; ``` ```java title="binary_tree.java" +/* 이진 트리 초기화 */ // 노드 초기화 TreeNode n1 = new TreeNode(1); TreeNode n2 = new TreeNode(2); TreeNode n3 = new TreeNode(3); TreeNode n4 = new TreeNode(4); TreeNode n5 = new TreeNode(5); -// 노드 사이의 참조(포인터) 연결 +// 노드 사이의 참조(포인터)를 설정한다 n1.left = n2; n1.right = n3; n2.left = n4; @@ -225,7 +224,7 @@ TreeNode n2 = new(2); TreeNode n3 = new(3); TreeNode n4 = new(4); TreeNode n5 = new(5); -// 노드 사이의 참조(포인터) 연결 +// 노드 사이의 참조(포인터)를 설정한다 n1.left = n2; n1.right = n3; n2.left = n4; @@ -240,7 +239,7 @@ n2 := NewTreeNode(2) n3 := NewTreeNode(3) n4 := NewTreeNode(4) n5 := NewTreeNode(5) -// 노드 사이의 참조(포인터) 연결 +// 노드 사이의 참조(포인터)를 설정한다 n1.Left = n2 n1.Right = n3 n2.Left = n4 @@ -248,13 +247,14 @@ n2.Right = n5 ``` ```swift title="binary_tree.swift" +/* 이진 트리 초기화 */ // 노드 초기화 let n1 = TreeNode(x: 1) let n2 = TreeNode(x: 2) let n3 = TreeNode(x: 3) let n4 = TreeNode(x: 4) let n5 = TreeNode(x: 5) -// 노드 사이의 참조(포인터) 연결 +// 노드 사이의 참조(포인터)를 설정한다 n1.left = n2 n1.right = n3 n2.left = n4 @@ -269,7 +269,7 @@ let n1 = new TreeNode(1), n3 = new TreeNode(3), n4 = new TreeNode(4), n5 = new TreeNode(5); -// 노드 사이의 참조(포인터) 연결 +// 노드 사이의 참조(포인터)를 설정한다 n1.left = n2; n1.right = n3; n2.left = n4; @@ -284,7 +284,7 @@ let n1 = new TreeNode(1), n3 = new TreeNode(3), n4 = new TreeNode(4), n5 = new TreeNode(5); -// 노드 사이의 참조(포인터) 연결 +// 노드 사이의 참조(포인터)를 설정한다 n1.left = n2; n1.right = n3; n2.left = n4; @@ -294,12 +294,12 @@ n2.right = n5; ```dart title="binary_tree.dart" /* 이진 트리 초기화 */ // 노드 초기화 -TreeNode n1 = new TreeNode(1); -TreeNode n2 = new TreeNode(2); -TreeNode n3 = new TreeNode(3); -TreeNode n4 = new TreeNode(4); -TreeNode n5 = new TreeNode(5); -// 노드 사이의 참조(포인터) 연결 +TreeNode n1 = TreeNode(1); +TreeNode n2 = TreeNode(2); +TreeNode n3 = TreeNode(3); +TreeNode n4 = TreeNode(4); +TreeNode n5 = TreeNode(5); +// 노드 사이의 참조(포인터)를 설정한다 n1.left = n2; n1.right = n3; n2.left = n4; @@ -307,17 +307,18 @@ n2.right = n5; ``` ```rust title="binary_tree.rs" +/* 이진 트리 초기화 */ // 노드 초기화 let n1 = TreeNode::new(1); let n2 = TreeNode::new(2); let n3 = TreeNode::new(3); let n4 = TreeNode::new(4); let n5 = TreeNode::new(5); -// 노드 사이의 참조(포인터) 연결 -n1.borrow_mut().left = Some(n2.clone()); -n1.borrow_mut().right = Some(n3); -n2.borrow_mut().left = Some(n4); -n2.borrow_mut().right = Some(n5); +// 노드 사이의 참조(포인터)를 설정한다 +n1.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().right = Some(Rc::clone(&n3)); +n2.borrow_mut().left = Some(Rc::clone(&n4)); +n2.borrow_mut().right = Some(Rc::clone(&n5)); ``` ```c title="binary_tree.c" @@ -328,7 +329,7 @@ TreeNode *n2 = newTreeNode(2); TreeNode *n3 = newTreeNode(3); TreeNode *n4 = newTreeNode(4); TreeNode *n5 = newTreeNode(5); -// 노드 사이의 참조(포인터) 연결 +// 노드 사이의 참조(포인터)를 설정한다 n1->left = n2; n1->right = n3; n2->left = n4; @@ -336,13 +337,14 @@ n2->right = n5; ``` ```kotlin title="binary_tree.kt" +/* 이진 트리 초기화 */ // 노드 초기화 val n1 = TreeNode(1) val n2 = TreeNode(2) val n3 = TreeNode(3) val n4 = TreeNode(4) val n5 = TreeNode(5) -// 노드 사이의 참조(포인터) 연결 +// 노드 사이의 참조(포인터)를 설정한다 n1.left = n2 n1.right = n3 n2.left = n4 @@ -357,7 +359,7 @@ n2 = TreeNode.new(2) n3 = TreeNode.new(3) n4 = TreeNode.new(4) n5 = TreeNode.new(5) -# 노드 사이의 참조(포인터) 연결 +# 노드 사이의 참조(포인터)를 설정한다 n1.left = n2 n1.right = n3 n2.left = n4 @@ -370,128 +372,132 @@ https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%2 ```python title="binary_tree.py" # 노드 삽입과 삭제 -p = TreeNode(0) -# n1 -> n2 사이에 노드 P 삽입 -n1.left = p -p.left = n2 -# 노드 P 삭제 +P = TreeNode(0) +# n1 -> n2 사이에 노드 P를 삽입한다 +n1.left = P +P.left = n2 +# 노드 P를 삭제한다 n1.left = n2 ``` ```cpp title="binary_tree.cpp" /* 노드 삽입과 삭제 */ -TreeNode* P = new TreeNode(0); -// n1 -> n2 사이에 노드 P 삽입 +TreeNode *P = new TreeNode(0); +// n1 -> n2 사이에 노드 P를 삽입한다 n1->left = P; P->left = n2; -// 노드 P 삭제 +// 노드 P를 삭제한다 n1->left = n2; -// 메모리 해제 -delete P; +delete P; // 메모리 해제 ``` ```java title="binary_tree.java" +/* 노드 삽입과 삭제 */ TreeNode P = new TreeNode(0); -// n1 -> n2 사이에 노드 P 삽입 +// n1 -> n2 사이에 노드 P를 삽입한다 n1.left = P; P.left = n2; -// 노드 P 삭제 +// 노드 P를 삭제한다 n1.left = n2; ``` ```csharp title="binary_tree.cs" /* 노드 삽입과 삭제 */ TreeNode P = new(0); -// n1 -> n2 사이에 노드 P 삽입 +// n1 -> n2 사이에 노드 P를 삽입한다 n1.left = P; P.left = n2; -// 노드 P 삭제 +// 노드 P를 삭제한다 n1.left = n2; ``` ```go title="binary_tree.go" /* 노드 삽입과 삭제 */ -// n1 -> n2 사이에 노드 P 삽입 +// n1 -> n2 사이에 노드 P를 삽입한다 p := NewTreeNode(0) n1.Left = p p.Left = n2 -// 노드 P 삭제 +// 노드 P를 삭제한다 n1.Left = n2 ``` ```swift title="binary_tree.swift" +/* 노드 삽입과 삭제 */ let P = TreeNode(x: 0) -// n1 -> n2 사이에 노드 P 삽입 +// n1 -> n2 사이에 노드 P를 삽입한다 n1.left = P P.left = n2 -// 노드 P 삭제 +// 노드 P를 삭제한다 n1.left = n2 ``` ```javascript title="binary_tree.js" /* 노드 삽입과 삭제 */ -let P = new TreeNode(0); -// n1 -> n2 사이에 노드 P 삽입 +const P = new TreeNode(0); +// n1 -> n2 사이에 노드 P를 삽입한다 n1.left = P; P.left = n2; -// 노드 P 삭제 +// 노드 P를 삭제한다 n1.left = n2; ``` ```typescript title="binary_tree.ts" /* 노드 삽입과 삭제 */ const P = new TreeNode(0); -// n1 -> n2 사이에 노드 P 삽입 +// n1 -> n2 사이에 노드 P를 삽입한다 n1.left = P; P.left = n2; -// 노드 P 삭제 +// 노드 P를 삭제한다 n1.left = n2; ``` ```dart title="binary_tree.dart" /* 노드 삽입과 삭제 */ -TreeNode P = new TreeNode(0); -// n1 -> n2 사이에 노드 P 삽입 -n1.left = P; -P.left = n2; -// 노드 P 삭제 +TreeNode p = TreeNode(0); +// n1 -> n2 사이에 노드 P를 삽입한다 +n1.left = p; +p.left = n2; +// 노드 P를 삭제한다 n1.left = n2; ``` ```rust title="binary_tree.rs" +/* 노드 삽입과 삭제 */ let p = TreeNode::new(0); -// n1 -> n2 사이에 노드 P 삽입 -n1.borrow_mut().left = Some(p.clone()); -p.borrow_mut().left = Some(n2.clone()); -// 노드 p 삭제 -n1.borrow_mut().left = Some(n2); +// n1 -> n2 사이에 노드 P를 삽입한다 +p.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().left = Some(Rc::clone(&p)); +// 노드 P를 삭제한다 +drop(p); +n1.borrow_mut().left = Some(Rc::clone(&n2)); ``` ```c title="binary_tree.c" /* 노드 삽입과 삭제 */ TreeNode *P = newTreeNode(0); -// n1 -> n2 사이에 노드 P 삽입 +// n1 -> n2 사이에 노드 P를 삽입한다 n1->left = P; P->left = n2; -// 노드 P 삭제 +// 노드 P를 삭제한다 n1->left = n2; // 메모리 해제 free(P); ``` ```kotlin title="binary_tree.kt" +/* 노드 삽입과 삭제 */ val P = TreeNode(0) -// n1 -> n2 사이에 노드 P 삽입 +// n1 -> n2 사이에 노드 P를 삽입한다 n1.left = P P.left = n2 -// 노드 P 삭제 +// 노드 P를 삭제한다 n1.left = n2 ``` ```ruby title="binary_tree.rb" # 노드 삽입과 삭제 _p = TreeNode.new(0) -# n1 -> n2 사이에 노드 _p 삽입 +# n1 -> n2 사이에 노드 _p를 삽입한다 n1.left = _p _p.left = n2 # 노드 삭제 @@ -499,4 +505,4 @@ n1.left = n2 ``` -https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%EC%99%BC%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%EC%98%A4%EB%A5%B8%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%AC%EC%9D%B4%EC%9D%98%20%EC%B0%B8%EC%A1%B0%28%ED%8F%AC%EC%9D%B8%ED%84%B0%29%20%EC%97%B0%EA%B2%B0%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%BD%EC%9E%85%EA%B3%BC%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20n1%20-%3E%20n2%20%EC%82%AC%EC%9D%B4%EC%97%90%20%EB%85%B8%EB%93%9C%20P%20%EC%82%BD%EC%9E%85%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20P%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EB%85%B8%EB%93%9C%20%ED%81%B4%EB%9E%98%EC%8A%A4%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EA%B0%92%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%EC%99%BC%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%EC%98%A4%EB%A5%B8%EC%AA%BD%20%EC%9E%90%EC%8B%9D%20%EB%85%B8%EB%93%9C%20%EC%B0%B8%EC%A1%B0%0A%0A%22%22%22%EC%8B%A4%ED%96%89%20%EC%BD%94%EB%93%9C%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%EC%9D%B4%EC%A7%84%20%ED%8A%B8%EB%A6%AC%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%B4%88%EA%B8%B0%ED%99%94%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%AC%EC%9D%B4%EC%9D%98%20%EC%B0%B8%EC%A1%B0%28%ED%8F%AC%EC%9D%B8%ED%84%B0%29%20%EC%97%B0%EA%B2%B0%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20%EC%82%BD%EC%9E%85%EA%B3%BC%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20P%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20n1%20-%3E%20n2%20%EC%82%AC%EC%9D%B4%EC%97%90%20%EB%85%B8%EB%93%9C%20P%20%EC%82%BD%EC%9E%85%0A%20%20%20%20n1.left%20%3D%20P%0A%20%20%20%20P.left%20%3D%20n2%0A%20%20%20%20%23%20%EB%85%B8%EB%93%9C%20P%20%EC%82%AD%EC%A0%9C%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ko/codes/swift/chapter_hashing/built_in_hash.swift b/ko/codes/swift/chapter_hashing/built_in_hash.swift index a3c346afa..876fd3d9d 100644 --- a/ko/codes/swift/chapter_hashing/built_in_hash.swift +++ b/ko/codes/swift/chapter_hashing/built_in_hash.swift @@ -12,15 +12,15 @@ enum BuiltInHash { static func main() { let num = 3 let hashNum = num.hashValue - print("정수 = \(num), 해시값 = \(hashNum)") + print("정수 \(num) → 해시값: \(hashNum)") let bol = true let hashBol = bol.hashValue - print("불리언 값 = \(bol), 해시값 = \(hashBol)") + print("불리언 값 \(bol) → 해시값: \(hashBol)") let dec = 3.14159 let hashDec = dec.hashValue - print("소수 = \(dec), 해시값 = \(hashDec)") + print("소수 \(dec) → 해시값: \(hashDec)") let str = "Hello 算法" let hashStr = str.hashValue @@ -32,6 +32,6 @@ enum BuiltInHash { let obj = ListNode(x: 0) let hashObj = obj.hashValue - print("노드 객체 = \(obj), 해시값 = \(hashObj)") + print("노드 객체 \(obj) → 해시값: \(hashObj)") } } diff --git a/ko/codes/swift/chapter_stack_and_queue/array_deque.swift b/ko/codes/swift/chapter_stack_and_queue/array_deque.swift index c9ca28de2..67eb97a2e 100644 --- a/ko/codes/swift/chapter_stack_and_queue/array_deque.swift +++ b/ko/codes/swift/chapter_stack_and_queue/array_deque.swift @@ -125,13 +125,13 @@ enum _ArrayDeque { let peekLast = deque.peekLast() print("맨 뒤 원소 peekLast = \(peekLast)") - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(num: 4) print("맨 뒤에 원소 4를 삽입한 후 deque = \(deque.toArray())") deque.pushFirst(num: 1) print("맨 앞에 원소 1을 삽입한 후 deque = \(deque.toArray())") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ let popLast = deque.popLast() print("맨 뒤에서 꺼낸 원소 = \(popLast), 꺼낸 후 deque = \(deque.toArray())") let popFirst = deque.popFirst() diff --git a/ko/codes/swift/chapter_stack_and_queue/array_queue.swift b/ko/codes/swift/chapter_stack_and_queue/array_queue.swift index e26fbb5d1..06a7a40c5 100644 --- a/ko/codes/swift/chapter_stack_and_queue/array_queue.swift +++ b/ko/codes/swift/chapter_stack_and_queue/array_queue.swift @@ -32,7 +32,7 @@ class ArrayQueue { size() == 0 } - /* 큐에 삽입 */ + /* 원소 삽입 */ func push(num: Int) { if size() == capacity() { print("큐가 가득 찼다") @@ -46,7 +46,7 @@ class ArrayQueue { _size += 1 } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ @discardableResult func pop() -> Int { let num = peek() @@ -79,7 +79,7 @@ enum _ArrayQueue { let capacity = 10 let queue = ArrayQueue(capacity: capacity) - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(num: 1) queue.push(num: 3) queue.push(num: 2) @@ -91,7 +91,7 @@ enum _ArrayQueue { let peek = queue.peek() print("맨 앞 원소 peek = \(peek)") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ let pop = queue.pop() print("큐에서 꺼낸 원소 pop = \(pop), 꺼낸 후 queue = \(queue.toArray())") @@ -107,7 +107,7 @@ enum _ArrayQueue { for i in 0 ..< 10 { queue.push(num: i) queue.pop() - print("반복 \(i): 삽입 + 꺼내기 후 queue = \(queue.toArray())") + print("반복 \(i) 회차에서 삽입 + 꺼내기를 수행한 후 queue = \(queue.toArray())") } } } diff --git a/ko/codes/swift/chapter_stack_and_queue/deque.swift b/ko/codes/swift/chapter_stack_and_queue/deque.swift index 5aa157919..eb82f3dd7 100644 --- a/ko/codes/swift/chapter_stack_and_queue/deque.swift +++ b/ko/codes/swift/chapter_stack_and_queue/deque.swift @@ -12,7 +12,7 @@ enum Deque { // Swift에는 내장 덱 클래스가 없으므로 Array를 덱으로 사용할 수 있다 var deque: [Int] = [] - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.append(2) deque.append(5) deque.append(4) @@ -26,8 +26,8 @@ enum Deque { let peekLast = deque.last! print("맨 뒤 원소 peekLast = \(peekLast)") - /* 큐에서 원소 꺼내기 */ - // Array로 구현할 때 popFirst의 시간 복잡도는 O(n)이다 + /* 원소 꺼내기 */ + // Array로 구현할 때 removeFirst의 복잡도는 O(n)이다 let popFirst = deque.removeFirst() print("맨 앞에서 꺼낸 원소 popFirst = \(popFirst), 꺼낸 후 deque = \(deque)") let popLast = deque.removeLast() diff --git a/ko/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift b/ko/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift index 6f6391c1a..94b6f7152 100644 --- a/ko/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift +++ b/ko/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift @@ -35,7 +35,7 @@ class LinkedListDeque { size() == 0 } - /* 큐 삽입 연산 */ + /* 원소 삽입 연산 */ private func push(num: Int, isFront: Bool) { let node = ListNode(val: num) // 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다 @@ -70,7 +70,7 @@ class LinkedListDeque { push(num: num, isFront: false) } - /* 큐에서 꺼내는 연산 */ + /* 원소를 꺼내는 연산 */ private func pop(isFront: Bool) -> Int { if isEmpty() { fatalError("덱이 비어 있다") @@ -159,13 +159,13 @@ enum _LinkedListDeque { let peekLast = deque.peekLast() print("맨 뒤 원소 peekLast = \(peekLast)") - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ deque.pushLast(num: 4) print("맨 뒤에 원소 4를 삽입한 후 deque = \(deque.toArray())") deque.pushFirst(num: 1) print("맨 앞에 원소 1을 삽입한 후 deque = \(deque.toArray())") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ let popLast = deque.popLast() print("맨 뒤에서 꺼낸 원소 = \(popLast), 꺼낸 후 deque = \(deque.toArray())") let popFirst = deque.popFirst() diff --git a/ko/codes/swift/chapter_stack_and_queue/linkedlist_queue.swift b/ko/codes/swift/chapter_stack_and_queue/linkedlist_queue.swift index b5f935347..22fc6d80d 100644 --- a/ko/codes/swift/chapter_stack_and_queue/linkedlist_queue.swift +++ b/ko/codes/swift/chapter_stack_and_queue/linkedlist_queue.swift @@ -26,7 +26,7 @@ class LinkedListQueue { size() == 0 } - /* 큐에 삽입 */ + /* 원소 삽입 */ func push(num: Int) { // 꼬리 노드 뒤에 num을 추가한다 let node = ListNode(x: num) @@ -43,7 +43,7 @@ class LinkedListQueue { _size += 1 } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ @discardableResult func pop() -> Int { let num = peek() @@ -80,7 +80,7 @@ enum _LinkedListQueue { /* 큐 초기화 */ let queue = LinkedListQueue() - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.push(num: 1) queue.push(num: 3) queue.push(num: 2) @@ -92,7 +92,7 @@ enum _LinkedListQueue { let peek = queue.peek() print("맨 앞 원소 peek = \(peek)") - /* 큐에서 원소 꺼내기 */ + /* 원소 꺼내기 */ let pop = queue.pop() print("큐에서 꺼낸 원소 pop = \(pop), 꺼낸 후 queue = \(queue.toArray())") diff --git a/ko/codes/swift/chapter_stack_and_queue/queue.swift b/ko/codes/swift/chapter_stack_and_queue/queue.swift index c3d864130..52a25ad43 100644 --- a/ko/codes/swift/chapter_stack_and_queue/queue.swift +++ b/ko/codes/swift/chapter_stack_and_queue/queue.swift @@ -12,7 +12,7 @@ enum Queue { // Swift에는 내장 큐 클래스가 없으므로 Array를 큐로 사용할 수 있다 var queue: [Int] = [] - /* 큐에 원소 삽입 */ + /* 원소 삽입 */ queue.append(1) queue.append(3) queue.append(2) @@ -24,8 +24,8 @@ enum Queue { let peek = queue.first! print("맨 앞 원소 peek = \(peek)") - /* 큐에서 원소 꺼내기 */ - // Array로 구현할 때 pop의 시간 복잡도는 O(n)이다 + /* 원소 꺼내기 */ + // Array로 구현할 때 removeFirst의 복잡도는 O(n)이다 let pop = queue.removeFirst() print("큐에서 꺼낸 원소 pop = \(pop), 꺼낸 후 queue = \(queue)") diff --git a/ko/codes/typescript/chapter_stack_and_queue/array_deque.ts b/ko/codes/typescript/chapter_stack_and_queue/array_deque.ts index 4232ea42d..f80cf9392 100644 --- a/ko/codes/typescript/chapter_stack_and_queue/array_deque.ts +++ b/ko/codes/typescript/chapter_stack_and_queue/array_deque.ts @@ -123,13 +123,13 @@ console.log('맨 앞 원소 peekFirst = ' + peekFirst); const peekLast = deque.peekLast(); console.log('맨 뒤 원소 peekLast = ' + peekLast); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ deque.pushLast(4); console.log('뒤쪽에 원소 4를 삽입한 후 deque = [' + deque.toArray() + ']'); deque.pushFirst(1); console.log('앞쪽에 원소 1을 삽입한 후 deque = [' + deque.toArray() + ']'); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ const popLast = deque.popLast(); console.log( '맨 뒤에서 꺼낸 원소 = ' + diff --git a/ko/codes/typescript/chapter_stack_and_queue/array_queue.ts b/ko/codes/typescript/chapter_stack_and_queue/array_queue.ts index 77e0fe1dc..00951a11f 100644 --- a/ko/codes/typescript/chapter_stack_and_queue/array_queue.ts +++ b/ko/codes/typescript/chapter_stack_and_queue/array_queue.ts @@ -30,7 +30,7 @@ class ArrayQueue { return this.queSize === 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ push(num: number): void { if (this.size === this.capacity) { console.log('큐가 가득 찼다'); @@ -44,7 +44,7 @@ class ArrayQueue { this.queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ pop(): number { const num = this.peek(); // 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다 @@ -75,7 +75,7 @@ class ArrayQueue { const capacity = 10; const queue = new ArrayQueue(capacity); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -87,7 +87,7 @@ console.log('큐 queue =', queue.toArray()); const peek = queue.peek(); console.log('맨 앞 원소 peek = ' + peek); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ const pop = queue.pop(); console.log('큐에서 꺼낸 원소 pop = ' + pop + ', 큐에서 꺼낸 후 queue =', queue.toArray()); @@ -103,7 +103,7 @@ console.log('큐가 비어 있는가 = ' + isEmpty); for (let i = 0; i < 10; i++) { queue.push(i); queue.pop(); - console.log('반복 ' + i + ' 회에서 삽입 + 꺼내기를 수행한 후 queue =', queue.toArray()); + console.log('반복 ' + i + ' 회차에서 삽입 + 꺼내기를 수행한 후 queue =', queue.toArray()); } export {}; diff --git a/ko/codes/typescript/chapter_stack_and_queue/deque.ts b/ko/codes/typescript/chapter_stack_and_queue/deque.ts index bc5354473..fb68e08f7 100644 --- a/ko/codes/typescript/chapter_stack_and_queue/deque.ts +++ b/ko/codes/typescript/chapter_stack_and_queue/deque.ts @@ -6,10 +6,10 @@ /* 실행 코드 */ /* 덱 초기화 */ -// TypeScript에는 내장 덱이 없으므로 Array를 덱으로 사용한다 +// TypeScript에는 내장 덱이 없으므로 Array를 덱으로 사용해야 한다 const deque: number[] = []; -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ deque.push(2); deque.push(5); deque.push(4); @@ -24,7 +24,7 @@ console.log('맨 앞 원소 peekFirst = ' + peekFirst); const peekLast: number = deque[deque.length - 1]; console.log('맨 뒤 원소 peekLast = ' + peekLast); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ // 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 유의한다 const popFront: number = deque.shift() as number; console.log( diff --git a/ko/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts b/ko/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts index 66582c3ac..99922b74a 100644 --- a/ko/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/ko/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -6,8 +6,8 @@ /* 이중 연결 리스트 노드 */ class ListNode { - prev: ListNode; // 이전 노드 참조(포인터) - next: ListNode; // 다음 노드 참조(포인터) + prev: ListNode | null; // 이전 노드 참조(포인터) + next: ListNode | null; // 다음 노드 참조(포인터) val: number; // 노드 값 constructor(val: number) { @@ -152,7 +152,7 @@ console.log('맨 앞 원소 peekFirst = ' + peekFirst); const peekLast: number = linkedListDeque.peekLast(); console.log('맨 뒤 원소 peekLast = ' + peekLast); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ linkedListDeque.pushLast(4); console.log('뒤쪽에 원소 4를 삽입한 후 linkedListDeque = '); linkedListDeque.print(); @@ -160,7 +160,7 @@ linkedListDeque.pushFirst(1); console.log('앞쪽에 원소 1을 삽입한 후 linkedListDeque = '); linkedListDeque.print(); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ const popLast: number = linkedListDeque.popLast(); console.log('맨 뒤에서 꺼낸 원소 = ' + popLast + ', 뒤쪽 원소를 꺼낸 후 linkedListDeque = '); linkedListDeque.print(); diff --git a/ko/codes/typescript/chapter_stack_and_queue/linkedlist_queue.ts b/ko/codes/typescript/chapter_stack_and_queue/linkedlist_queue.ts index 08eed5b2c..20504d6a1 100644 --- a/ko/codes/typescript/chapter_stack_and_queue/linkedlist_queue.ts +++ b/ko/codes/typescript/chapter_stack_and_queue/linkedlist_queue.ts @@ -27,7 +27,7 @@ class LinkedListQueue { return this.size === 0; } - /* 큐에 삽입 */ + /* 원소 삽입 */ push(num: number): void { // 꼬리 노드 뒤에 num을 추가한다 const node = new ListNode(num); @@ -43,7 +43,7 @@ class LinkedListQueue { this.queSize++; } - /* 큐에서 꺼내기 */ + /* 원소 꺼내기 */ pop(): number { const num = this.peek(); if (!this.front) throw new Error('큐가 비어 있다'); @@ -75,7 +75,7 @@ class LinkedListQueue { /* 큐 초기화 */ const queue = new LinkedListQueue(); -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -87,7 +87,7 @@ console.log('큐 queue = ' + queue.toArray()); const peek = queue.peek(); console.log('맨 앞 원소 peek = ' + peek); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ const pop = queue.pop(); console.log('큐에서 꺼낸 원소 pop = ' + pop + ', 큐에서 꺼낸 후 queue = ' + queue.toArray()); diff --git a/ko/codes/typescript/chapter_stack_and_queue/queue.ts b/ko/codes/typescript/chapter_stack_and_queue/queue.ts index 6a506fe44..370ac08b8 100644 --- a/ko/codes/typescript/chapter_stack_and_queue/queue.ts +++ b/ko/codes/typescript/chapter_stack_and_queue/queue.ts @@ -9,7 +9,7 @@ // TypeScript에는 내장 큐가 없으므로 Array를 큐로 사용할 수 있다 const queue: number[] = []; -/* 큐에 원소 삽입 */ +/* 원소 삽입 */ queue.push(1); queue.push(3); queue.push(2); @@ -21,7 +21,7 @@ console.log('큐 queue =', queue); const peek = queue[0]; console.log('맨 앞 원소 peek =', peek); -/* 큐에서 원소 꺼내기 */ +/* 원소 꺼내기 */ // 내부 자료 구조가 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다 const pop = queue.shift(); console.log('큐에서 꺼낸 원소 pop =', pop, ', 큐에서 꺼낸 후 queue = ', queue); diff --git a/ru/codes/c/chapter_array_and_linkedlist/array.c b/ru/codes/c/chapter_array_and_linkedlist/array.c index fb9524dc2..b3e07e574 100644 --- a/ru/codes/c/chapter_array_and_linkedlist/array.c +++ b/ru/codes/c/chapter_array_and_linkedlist/array.c @@ -75,7 +75,7 @@ int main() { /* Инициализация массива */ int size = 5; - int arr[5]; + int arr[5] = {0}; printf("Массив arr = "); printArray(arr, size); diff --git a/ru/codes/c/utils/list_node.h b/ru/codes/c/utils/list_node.h index 76775e419..6c5301335 100644 --- a/ru/codes/c/utils/list_node.h +++ b/ru/codes/c/utils/list_node.h @@ -14,7 +14,7 @@ extern "C" { /* Структура узла связного списка */ typedef struct ListNode { int val; // Значение узла - struct ListNode *next; // Ссылка на следующий узел + struct ListNode *next; // Указатель на следующий узел } ListNode; /* Конструктор, инициализирующий новый узел */ diff --git a/ru/codes/cpp/chapter_array_and_linkedlist/array.cpp b/ru/codes/cpp/chapter_array_and_linkedlist/array.cpp index 00b77cae0..d82587fe7 100644 --- a/ru/codes/cpp/chapter_array_and_linkedlist/array.cpp +++ b/ru/codes/cpp/chapter_array_and_linkedlist/array.cpp @@ -18,7 +18,7 @@ int randomAccess(int *nums, int size) { /* Увеличение длины массива */ int *extend(int *nums, int size, int enlarge) { // Инициализировать массив увеличенной длины - int *res = new int[size + enlarge]; + int *res = new int[size + enlarge]{}; // Скопировать все элементы исходного массива в новый массив for (int i = 0; i < size; i++) { res[i] = nums[i]; @@ -69,7 +69,7 @@ int find(int *nums, int size, int target) { int main() { /* Инициализация массива */ int size = 5; - int *arr = new int[size]; + int *arr = new int[size]{}; cout << "Массив arr = "; printArray(arr, size); diff --git a/ru/codes/dart/chapter_hashing/hash_map.dart b/ru/codes/dart/chapter_hashing/hash_map.dart index 674d7d93c..9db68576e 100644 --- a/ru/codes/dart/chapter_hashing/hash_map.dart +++ b/ru/codes/dart/chapter_hashing/hash_map.dart @@ -36,6 +36,5 @@ void main() { print("\nОтдельный обход ключей"); map.keys.forEach((key) => print(key)); print("\nОтдельный обход значений"); - map.forEach((key, value) => print("$value")); map.values.forEach((value) => print(value)); } diff --git a/ru/codes/go/chapter_heap/heap_test.go b/ru/codes/go/chapter_heap/heap_test.go index e96783a74..71e8b6c8c 100644 --- a/ru/codes/go/chapter_heap/heap_test.go +++ b/ru/codes/go/chapter_heap/heap_test.go @@ -91,8 +91,6 @@ func TestMyHeap(t *testing.T) { } func TestTopKHeap(t *testing.T) { - /* Инициализация кучи */ - // Инициализация максимальной кучи nums := []int{1, 7, 6, 3, 2} k := 3 res := topKHeap(nums, k) diff --git a/ru/codes/go/chapter_stack_and_queue/deque_test.go b/ru/codes/go/chapter_stack_and_queue/deque_test.go index 0b0be8681..d4c2d46b7 100644 --- a/ru/codes/go/chapter_stack_and_queue/deque_test.go +++ b/ru/codes/go/chapter_stack_and_queue/deque_test.go @@ -51,7 +51,6 @@ func TestDeque(t *testing.T) { func TestArrayDeque(t *testing.T) { /* Инициализация двусторонней очереди */ - // В Go list используется как двусторонняя очередь deque := newArrayDeque(16) /* Добавление элемента в очередь */ @@ -102,7 +101,7 @@ func TestLinkedListDeque(t *testing.T) { deque.pushLast(4) deque.pushFirst(3) deque.pushFirst(1) - fmt.Print("Очередь deque = ") + fmt.Print("Двусторонняя очередь deque = ") PrintList(deque.toList()) // Доступ к элементу в начале очереди diff --git a/ru/codes/java/chapter_array_and_linkedlist/list.java b/ru/codes/java/chapter_array_and_linkedlist/list.java index 723c4435f..c437c36b6 100644 --- a/ru/codes/java/chapter_array_and_linkedlist/list.java +++ b/ru/codes/java/chapter_array_and_linkedlist/list.java @@ -11,7 +11,7 @@ import java.util.*; public class list { public static void main(String[] args) { /* Инициализация списка */ - // Обратите внимание: тип элементов массива int[] — это обертка Integer[] + // Обратите внимание: массив должен иметь тип Integer[], а не int[], поскольку элементами списка могут быть только объекты класса-обертки Integer Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); System.out.println("Список nums = " + nums); diff --git a/ru/codes/python/chapter_hashing/built_in_hash.py b/ru/codes/python/chapter_hashing/built_in_hash.py index 85dc95db4..84db4adef 100644 --- a/ru/codes/python/chapter_hashing/built_in_hash.py +++ b/ru/codes/python/chapter_hashing/built_in_hash.py @@ -30,7 +30,7 @@ if __name__ == "__main__": tup = (12836, "Сяо Ха") hash_tup = hash(tup) - print(f"Хеш-значение кортежа {tup} = {hash(hash_tup)}") + print(f"Хеш-значение кортежа {tup} = {hash_tup}") obj = ListNode(0) hash_obj = hash(obj) diff --git a/ru/codes/ruby/chapter_hashing/built_in_hash.rb b/ru/codes/ruby/chapter_hashing/built_in_hash.rb index d40bcc3ac..b21616be9 100644 --- a/ru/codes/ruby/chapter_hashing/built_in_hash.rb +++ b/ru/codes/ruby/chapter_hashing/built_in_hash.rb @@ -24,9 +24,9 @@ if __FILE__ == $0 hash_str = str.hash puts "Хеш-значение строки #{str}: #{hash_str}" - tup = [12836, 'Сяо Ха'] - hash_tup = tup.hash - puts "Хеш-значение кортежа #{tup}: #{hash_tup}" + arr = [12836, 'Сяо Ха'] + hash_arr = arr.hash + puts "Хеш-значение массива #{arr}: #{hash_arr}" obj = ListNode.new(0) hash_obj = obj.hash diff --git a/ru/codes/ruby/chapter_stack_and_queue/array_deque.rb b/ru/codes/ruby/chapter_stack_and_queue/array_deque.rb index 6b86d24cc..652411a9f 100644 --- a/ru/codes/ruby/chapter_stack_and_queue/array_deque.rb +++ b/ru/codes/ruby/chapter_stack_and_queue/array_deque.rb @@ -127,7 +127,7 @@ if __FILE__ == $0 deque.push_last(4) puts "После добавления элемента 4 в хвост deque = #{deque.to_array}" deque.push_first(1) - puts "После добавления элемента 1 в хвост deque = #{deque.to_array}" + puts "После добавления элемента 1 в голову deque = #{deque.to_array}" # Извлечение элемента из очереди pop_last = deque.pop_last diff --git a/ru/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb b/ru/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb index ba5b5a73b..14642ea99 100644 --- a/ru/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/ru/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,7 +4,7 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end -### Узел двусвязного списка +### Узел двусвязного списка ### class ListNode attr_accessor :val attr_accessor :next # Ссылка на узел-преемник @@ -101,7 +101,7 @@ class LinkedListDeque pop(true) end - ### Извлечение из головы очереди ### + ### Извлечение из хвоста очереди ### def pop_last pop(false) end diff --git a/ru/codes/rust/chapter_hashing/hash_map_chaining.rs b/ru/codes/rust/chapter_hashing/hash_map_chaining.rs index 72384cc49..e0b6c2677 100644 --- a/ru/codes/rust/chapter_hashing/hash_map_chaining.rs +++ b/ru/codes/rust/chapter_hashing/hash_map_chaining.rs @@ -145,7 +145,11 @@ pub fn main() { /* Операция поиска */ // Ввести в хеш-таблицу ключ key и получить значение value println!( - "\nПо номеру 13276 найдено имя {}",\nmatch map.get(13276) {\n Some(value) => value,\n None => "Not a valid Key",\n} + "\nПо номеру 13276 найдено имя {}", + match map.get(13276) { + Some(value) => value, + None => "Not a valid Key", + } ); /* Операция удаления */ diff --git a/ru/codes/rust/chapter_tree/array_binary_tree.rs b/ru/codes/rust/chapter_tree/array_binary_tree.rs index 301aa6834..f9b0bb624 100644 --- a/ru/codes/rust/chapter_tree/array_binary_tree.rs +++ b/ru/codes/rust/chapter_tree/array_binary_tree.rs @@ -144,7 +144,13 @@ fn main() { let r = abt.right(i); let p = abt.parent(i); println!( - "\nТекущий индекс узла = {}, значение = {}",\ni,\nif let Some(val) = abt.val(i) {\n format!("{val}")\n} else {\n "null".to_string()\n} + "\nТекущий индекс узла = {}, значение = {}", + i, + if let Some(val) = abt.val(i) { + format!("{val}") + } else { + "null".to_string() + } ); println!( "Индекс левого дочернего узла = {}, значение = {}", diff --git a/ru/codes/rust/chapter_tree/avl_tree.rs b/ru/codes/rust/chapter_tree/avl_tree.rs index 0393a04ee..ac12dfd68 100644 --- a/ru/codes/rust/chapter_tree/avl_tree.rs +++ b/ru/codes/rust/chapter_tree/avl_tree.rs @@ -289,7 +289,9 @@ fn main() { let node = avl_tree.search(7); if let Some(node) = node { println!( - "\nНайденный объект узла = {:?}, значение узла = {}",\n&*node.borrow(),\nnode.borrow().val + "\nНайденный объект узла = {:?}, значение узла = {}", + &*node.borrow(), + node.borrow().val ); } } diff --git a/ru/codes/rust/chapter_tree/binary_search_tree.rs b/ru/codes/rust/chapter_tree/binary_search_tree.rs index 564add1ab..fe76f4980 100644 --- a/ru/codes/rust/chapter_tree/binary_search_tree.rs +++ b/ru/codes/rust/chapter_tree/binary_search_tree.rs @@ -172,7 +172,9 @@ fn main() { /* Найти узел */ let node = bst.search(7); println!( - "\nНайденный объект узла = {:?}, значение узла = {}",\nnode.clone().unwrap(),\nnode.clone().unwrap().borrow().val + "\nНайденный объект узла = {:?}, значение узла = {}", + node.clone().unwrap(), + node.clone().unwrap().borrow().val ); /* Вставка узла */ diff --git a/ru/codes/snippets/chapter_array_and_linkedlist/array.md b/ru/codes/snippets/chapter_array_and_linkedlist/array.md index 53595cac5..7ea3a69da 100644 --- a/ru/codes/snippets/chapter_array_and_linkedlist/array.md +++ b/ru/codes/snippets/chapter_array_and_linkedlist/array.md @@ -9,10 +9,10 @@ nums: list[int] = [1, 3, 2, 5, 4] /* Инициализация массива */ // Хранится в стеке int arr[5] = {}; -int nums[5] = { 1, 3, 2, 5, 4 }; +int nums[5] = {1, 3, 2, 5, 4}; // Хранится в куче (требуется ручное освобождение памяти) -int* arr1 = new int[5] {}; -int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +int *arr1 = new int[5]{}; +int *nums1 = new int[5]{1, 3, 2, 5, 4}; ``` ```java title="array.java" @@ -22,7 +22,7 @@ int[] nums = { 1, 3, 2, 5, 4 }; ``` ```csharp title="array.cs" -/* Инициализация массива */ +// Инициализация массива int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] int[] nums = [1, 3, 2, 5, 4]; ``` @@ -30,56 +30,55 @@ int[] nums = [1, 3, 2, 5, 4]; ```go title="array.go" /* Инициализация массива */ var arr [5]int -// В Go указание длины ([5]int) создает массив, а отсутствие длины ([]int) - срез -// Поскольку длина массива в Go определяется на этапе компиляции, для задания длины можно использовать только константы -// Чтобы упростить реализацию метода extend(), ниже будем рассматривать срезы (Slice) как массивы (Array) +// В Go при указании длины ([5]int) получается массив, а без указания длины ([]int) — срез +// Так как массивы в Go имеют длину, определяемую на этапе компиляции, для задания длины можно использовать только константы +// Для удобства реализации функции расширения extend() ниже срез (Slice) рассматривается как массив (Array) nums := []int{1, 3, 2, 5, 4} ``` ```swift title="array.swift" /* Инициализация массива */ let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] -let nums = [1, 3, 2, 5, 4] +var nums = [1, 3, 2, 5, 4] ``` ```javascript title="array.js" /* Инициализация массива */ -var arr = new Array(5).fill(0); -var nums = [1, 3, 2, 5, 4]; +const arr = new Array(5).fill(0); +let nums = [1, 3, 2, 5, 4]; ``` ```typescript title="array.ts" /* Инициализация массива */ -let arr: number[] = new Array(5).fill(0); +const arr: number[] = new Array(5).fill(0); let nums: number[] = [1, 3, 2, 5, 4]; ``` ```dart title="array.dart" /* Инициализация массива */ -List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +var arr = List.filled(5, 0); // [0, 0, 0, 0, 0] List nums = [1, 3, 2, 5, 4]; ``` ```rust title="array.rs" /* Инициализация массива */ let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] -let slice: &[i32] = &[0; 5]; -// В Rust указание длины ([i32; 5]) создает массив, а отсутствие длины (&[i32]) - срез -// Поскольку длина массива в Rust определяется на этапе компиляции, для задания длины можно использовать только константы -// Vector в Rust обычно используется как динамический массив -// Чтобы упростить реализацию метода extend(), ниже будем рассматривать vector как массив (array) +// В Rust при указании длины ([i32; 5]) получается массив, а без указания длины (&[i32]) — срез +// Так как массивы в Rust имеют длину, определяемую на этапе компиляции, для задания длины можно использовать только константы +// Vector обычно используется в Rust как тип динамического массива +// Для удобства реализации метода расширения extend() ниже vector рассматривается как массив (array) let nums: Vec = vec![1, 3, 2, 5, 4]; ``` ```c title="array.c" /* Инициализация массива */ -int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } -int nums[5] = { 1, 3, 2, 5, 4 }; +int arr[5] = {0}; // { 0, 0, 0, 0, 0 } +int nums[] = {1, 3, 2, 5, 4}; ``` ```kotlin title="array.kt" /* Инициализация массива */ -var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +val arr = IntArray(5) // { 0, 0, 0, 0, 0 } var nums = intArrayOf(1, 3, 2, 5, 4) ``` diff --git a/ru/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/ru/codes/snippets/chapter_array_and_linkedlist/linked_list.md index a60a52b37..ceefc613a 100644 --- a/ru/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/ru/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -2,48 +2,53 @@ ```python title="" class ListNode: """Класс узла связного списка""" + def __init__(self, val: int): - self.val: int = val # Значение узла - self.next: ListNode | None = None # Ссылка на следующий узел + self.val: int = val # Значение узла + self.next: ListNode | None = None # Ссылка на следующий узел ``` ```cpp title="" -/* Структура узла связного списка */ +/* Узел связного списка */ struct ListNode { - int val; // Значение узла - ListNode *next; // Указатель на следующий узел - ListNode(int x) : val(x), next(nullptr) {} // Конструктор + int val; // Значение узла + ListNode *next; // Указатель на узел-преемник + ListNode(int x) : val(x), next(nullptr) { + } }; ``` ```java title="" -/* Класс узла связного списка */ -class ListNode { - int val; // Значение узла - ListNode next; // Ссылка на следующий узел - ListNode(int x) { val = x; } // Конструктор +/* Узел связного списка */ +public class ListNode { + public int val; // Значение узла + public ListNode next; // Ссылка на следующий узел + + public ListNode(int x) { + val = x; + } } ``` ```csharp title="" -/* Класс узла связного списка */ -class ListNode(int x) { // Конструктор - public int val = x; // Значение узла - public ListNode? next; // Ссылка на следующий узел +/* Узел связного списка */ +public class ListNode(int x) { + public int val = x; // Значение узла + public ListNode? next; // Ссылка на следующий узел } ``` ```go title="" -/* Структура узла связного списка */ +// ListNode: узел связного списка type ListNode struct { Val int // Значение узла - Next *ListNode // Указатель на следующий узел + Next *ListNode // Указатель на узел-преемник } -// NewListNode — функция-конструктор, создающая новый связный список. -func NewListNode(val int) *ListNode { +// NewListNode: конструктор узла связного списка +func NewListNode(v int) *ListNode { return &ListNode{ - Val: val, + Val: v, Next: nil, } } @@ -62,44 +67,54 @@ class ListNode { ``` ```javascript title="" -/* Класс узла связного списка */ +/* Узел связного списка */ class ListNode { + val; // Значение узла + next; // Ссылка (указатель) на следующий узел constructor(val, next) { - this.val = (val === undefined ? 0 : val); // Значение узла - this.next = (next === undefined ? null : next); // Ссылка на следующий узел + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```typescript title="" -/* Класс узла связного списка */ +/* Узел связного списка */ class ListNode { - val: number; - next: ListNode | null; + val: number; // Значение узла + next: ListNode | null; // Ссылка на следующий узел constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // Значение узла - this.next = next === undefined ? null : next; // Ссылка на следующий узел + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```dart title="" -/* Класс узла связного списка */ +/* Узел связного списка */ class ListNode { int val; // Значение узла ListNode? next; // Ссылка на следующий узел + ListNode(this.val, [this.next]); // Конструктор } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; -/* Класс узла связного списка */ +use std::rc::Rc; + +/* Узел связного списка */ #[derive(Debug)] -struct ListNode { - val: i32, // Значение узла - next: Option>>, // Указатель на следующий узел +pub struct ListNode { + pub val: T, // Значение узла + pub next: Option>>>, // Указатель на узел-преемник +} + +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None })) + } } ``` @@ -110,10 +125,10 @@ typedef struct ListNode { struct ListNode *next; // Указатель на следующий узел } ListNode; -/* Конструктор */ +/* Конструктор, инициализирующий новый узел */ ListNode *newListNode(int val) { ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); + node = (ListNode *)malloc(sizeof(ListNode)); node->val = val; node->next = NULL; return node; @@ -121,16 +136,14 @@ ListNode *newListNode(int val) { ``` ```kotlin title="" -/* Класс узла связного списка */ -// Конструктор -class ListNode(x: Int) { - val _val: Int = x // Значение узла +/* Узел связного списка */ +class ListNode(var _val: Int) { var next: ListNode? = null // Ссылка на следующий узел } ``` ```ruby title="" -# Класс узла связного списка +### Класс узла связного списка ### class ListNode attr_accessor :val # Значение узла attr_accessor :next # Ссылка на следующий узел @@ -145,13 +158,13 @@ end ```python title="linked_list.py" # Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 -# Инициализация каждого узла +# Инициализация всех узлов n0 = ListNode(1) n1 = ListNode(3) n2 = ListNode(2) n3 = ListNode(5) n4 = ListNode(4) -# Построение ссылок между узлами +# Построить ссылки между узлами n0.next = n1 n1.next = n2 n2.next = n3 @@ -160,13 +173,13 @@ n3.next = n4 ```cpp title="linked_list.cpp" /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла -ListNode* n0 = new ListNode(1); -ListNode* n1 = new ListNode(3); -ListNode* n2 = new ListNode(2); -ListNode* n3 = new ListNode(5); -ListNode* n4 = new ListNode(4); -// Построение ссылок между узлами +// Инициализация всех узлов +ListNode *n0 = new ListNode(1); +ListNode *n1 = new ListNode(3); +ListNode *n2 = new ListNode(2); +ListNode *n3 = new ListNode(5); +ListNode *n4 = new ListNode(4); +// Построить ссылки между узлами n0->next = n1; n1->next = n2; n2->next = n3; @@ -175,13 +188,13 @@ n3->next = n4; ```java title="linked_list.java" /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла +// Инициализация всех узлов ListNode n0 = new ListNode(1); ListNode n1 = new ListNode(3); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(5); ListNode n4 = new ListNode(4); -// Построение ссылок между узлами +// Построить ссылки между узлами n0.next = n1; n1.next = n2; n2.next = n3; @@ -189,14 +202,14 @@ n3.next = n4; ``` ```csharp title="linked_list.cs" -/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла +// Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 +// Инициализация всех узлов ListNode n0 = new(1); ListNode n1 = new(3); ListNode n2 = new(2); ListNode n3 = new(5); ListNode n4 = new(4); -// Построение ссылок между узлами +// Построить ссылки между узлами n0.next = n1; n1.next = n2; n2.next = n3; @@ -204,14 +217,15 @@ n3.next = n4; ``` ```go title="linked_list.go" -/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла +/* Инициализировать связный список 1 -> 3 -> 2 -> 5 -> 4 */ +// Инициализация всех узлов n0 := NewListNode(1) n1 := NewListNode(3) n2 := NewListNode(2) n3 := NewListNode(5) n4 := NewListNode(4) -// Построение ссылок между узлами + +// Построить ссылки между узлами n0.Next = n1 n1.Next = n2 n2.Next = n3 @@ -220,13 +234,13 @@ n3.Next = n4 ```swift title="linked_list.swift" /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла +// Инициализация всех узлов let n0 = ListNode(x: 1) let n1 = ListNode(x: 3) let n2 = ListNode(x: 2) let n3 = ListNode(x: 5) let n4 = ListNode(x: 4) -// Построение ссылок между узлами +// Построить ссылки между узлами n0.next = n1 n1.next = n2 n2.next = n3 @@ -235,13 +249,13 @@ n3.next = n4 ```javascript title="linked_list.js" /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла +// Инициализация всех узлов const n0 = new ListNode(1); const n1 = new ListNode(3); const n2 = new ListNode(2); const n3 = new ListNode(5); const n4 = new ListNode(4); -// Построение ссылок между узлами +// Построить ссылки между узлами n0.next = n1; n1.next = n2; n2.next = n3; @@ -250,13 +264,13 @@ n3.next = n4; ```typescript title="linked_list.ts" /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла +// Инициализация всех узлов const n0 = new ListNode(1); const n1 = new ListNode(3); const n2 = new ListNode(2); const n3 = new ListNode(5); const n4 = new ListNode(4); -// Построение ссылок между узлами +// Построить ссылки между узлами n0.next = n1; n1.next = n2; n2.next = n3; @@ -264,14 +278,14 @@ n3.next = n4; ``` ```dart title="linked_list.dart" -/* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла +// Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 +// Инициализация всех узлов ListNode n0 = ListNode(1); ListNode n1 = ListNode(3); ListNode n2 = ListNode(2); ListNode n3 = ListNode(5); ListNode n4 = ListNode(4); -// Построение ссылок между узлами +// Построить ссылки между узлами n0.next = n1; n1.next = n2; n2.next = n3; @@ -280,14 +294,14 @@ n3.next = n4; ```rust title="linked_list.rs" /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла -let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); -let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); -let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); -let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); -let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); +// Инициализация всех узлов +let n0 = ListNode::new(1); +let n1 = ListNode::new(3); +let n2 = ListNode::new(2); +let n3 = ListNode::new(5); +let n4 = ListNode::new(4); -// Построение ссылок между узлами +// Построить ссылки между узлами n0.borrow_mut().next = Some(n1.clone()); n1.borrow_mut().next = Some(n2.clone()); n2.borrow_mut().next = Some(n3.clone()); @@ -296,13 +310,13 @@ n3.borrow_mut().next = Some(n4.clone()); ```c title="linked_list.c" /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла -ListNode* n0 = newListNode(1); -ListNode* n1 = newListNode(3); -ListNode* n2 = newListNode(2); -ListNode* n3 = newListNode(5); -ListNode* n4 = newListNode(4); -// Построение ссылок между узлами +// Инициализация всех узлов +ListNode *n0 = newListNode(1); +ListNode *n1 = newListNode(3); +ListNode *n2 = newListNode(2); +ListNode *n3 = newListNode(5); +ListNode *n4 = newListNode(4); +// Построить ссылки между узлами n0->next = n1; n1->next = n2; n2->next = n3; @@ -311,28 +325,29 @@ n3->next = n4; ```kotlin title="linked_list.kt" /* Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 */ -// Инициализация каждого узла +// Инициализация всех узлов val n0 = ListNode(1) val n1 = ListNode(3) val n2 = ListNode(2) val n3 = ListNode(5) val n4 = ListNode(4) -// Построение ссылок между узлами -n0.next = n1; -n1.next = n2; -n2.next = n3; -n3.next = n4; + +// Построить ссылки между узлами +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 ``` ```ruby title="linked_list.rb" # Инициализация связного списка 1 -> 3 -> 2 -> 5 -> 4 -# Инициализация каждого узла +# Инициализация всех узлов n0 = ListNode.new(1) n1 = ListNode.new(3) n2 = ListNode.new(2) n3 = ListNode.new(5) n4 = ListNode.new(4) -# Построение ссылок между узлами +# Построить ссылки между узлами n0.next = n1 n1.next = n2 n2.next = n3 @@ -345,39 +360,46 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2 ```python title="" class ListNode: - """Класс узла двусвязного списка""" + """Узел двусвязного списка""" + def __init__(self, val: int): - self.val: int = val # Значение узла - self.next: ListNode | None = None # Ссылка на следующий узел - self.prev: ListNode | None = None # Ссылка на предыдущий узел + """Конструктор""" + self.val: int = val # Значение узла + self.next: ListNode | None = None # Ссылка на узел-преемник + self.prev: ListNode | None = None # Ссылка на узел-предшественник ``` ```cpp title="" -/* Структура узла двусвязного списка */ -struct ListNode { - int val; // Значение узла - ListNode *next; // Указатель на следующий узел - ListNode *prev; // Указатель на предыдущий узел - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // Конструктор +/* Узел двусвязного списка */ +struct DoublyListNode { + int val; // Значение узла + DoublyListNode *next; // Указатель на узел-преемник + DoublyListNode *prev; // Указатель на узел-предшественник + DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { + } }; ``` ```java title="" -/* Класс узла двусвязного списка */ +/* Узел двусвязного списка */ class ListNode { - int val; // Значение узла - ListNode next; // Ссылка на следующий узел - ListNode prev; // Ссылка на предыдущий узел - ListNode(int x) { val = x; } // Конструктор + int val; // Значение узла + ListNode next; // Ссылка на узел-преемник + ListNode prev; // Ссылка на узел-предшественник + + ListNode(int val) { + this.val = val; + prev = next = null; + } } ``` ```csharp title="" -/* Класс узла двусвязного списка */ -class ListNode(int x) { // Конструктор - public int val = x; // Значение узла - public ListNode? next; // Ссылка на следующий узел - public ListNode? prev; // Ссылка на предыдущий узел +/* Узел двусвязного списка */ +public class ListNode(int val) { + public int val = val; // Значение узла + public ListNode? next = null; // Ссылка на узел-преемник + public ListNode? prev = null; // Ссылка на узел-предшественник } ``` @@ -385,8 +407,8 @@ class ListNode(int x) { // Конструктор /* Структура узла двусвязного списка */ type DoublyListNode struct { Val int // Значение узла - Next *DoublyListNode // Указатель на следующий узел - Prev *DoublyListNode // Указатель на предыдущий узел + Next *DoublyListNode // Указатель на узел-преемник + Prev *DoublyListNode // Указатель на узел-предшественник } // NewDoublyListNode инициализирует узел двусвязного списка. @@ -400,117 +422,119 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* Класс узла двусвязного списка */ +/* Узел двусвязного списка */ class ListNode { var val: Int // Значение узла - var next: ListNode? // Ссылка на следующий узел - var prev: ListNode? // Ссылка на предыдущий узел + var next: ListNode? // Ссылка на узел-преемник + weak var prev: ListNode? // Ссылка на узел-предшественник - init(x: Int) { // Конструктор - val = x + init(val: Int) { + self.val = val } } ``` ```javascript title="" -/* Класс узла двусвязного списка */ +/* Узел двусвязного списка */ class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // Значение узла - this.next = next === undefined ? null : next; // Ссылка на следующий узел - this.prev = prev === undefined ? null : prev; // Ссылка на предыдущий узел + prev; // Ссылка на узел-предшественник (указатель) + next; // Ссылка на узел-преемник (указатель) + val; // Значение узла + + constructor(val) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```typescript title="" -/* Класс узла двусвязного списка */ +/* Узел двусвязного списка */ class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // Значение узла - this.next = next === undefined ? null : next; // Ссылка на следующий узел - this.prev = prev === undefined ? null : prev; // Ссылка на предыдущий узел + prev: ListNode | null; // Ссылка на узел-предшественник (указатель) + next: ListNode | null; // Ссылка на узел-преемник (указатель) + val: number; // Значение узла + + constructor(val: number) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```dart title="" -/* Класс узла двусвязного списка */ +/* Узел двусвязного списка */ class ListNode { - int val; // Значение узла - ListNode? next; // Ссылка на следующий узел - ListNode? prev; // Ссылка на предыдущий узел - ListNode(this.val, [this.next, this.prev]); // Конструктор + int val; // Значение узла + ListNode? next; // Ссылка на узел-преемник + ListNode? prev; // Ссылка на узел-предшественник + + ListNode(this.val, {this.next, this.prev}); } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; -/* Тип узла двусвязного списка */ -#[derive(Debug)] -struct ListNode { - val: i32, // Значение узла - next: Option>>, // Указатель на следующий узел - prev: Option>>, // Указатель на предыдущий узел +/* Узел двусвязного списка */ +pub struct ListNode { + pub val: T, // Значение узла + pub next: Option>>>, // Указатель на узел-преемник + pub prev: Option>>>, // Указатель на узел-предшественник } -/* Конструктор */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None, prev: None, - } + })) } } ``` ```c title="" -/* Структура узла двусвязного списка */ -typedef struct ListNode { - int val; // Значение узла - struct ListNode *next; // Указатель на следующий узел - struct ListNode *prev; // Указатель на предыдущий узел -} ListNode; +/* Узел двусвязного списка */ +typedef struct DoublyListNode { + int val; // Значение узла + struct DoublyListNode *next; // Указатель на узел-преемник + struct DoublyListNode *prev; // Указатель на узел-предшественник +} DoublyListNode; /* Конструктор */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; +DoublyListNode *newDoublyListNode(int num) { + DoublyListNode *new = (DoublyListNode *)malloc(sizeof(DoublyListNode)); + new->val = num; + new->next = NULL; + new->prev = NULL; + return new; } ``` ```kotlin title="" -/* Класс узла двусвязного списка */ -// Конструктор -class ListNode(x: Int) { - val _val: Int = x // Значение узла - var next: ListNode? = null // Ссылка на следующий узел - var prev: ListNode? = null // Ссылка на предыдущий узел +/* Узел двусвязного списка */ +class ListNode( + var _val: Int // Значение узла +) { + var next: ListNode? = null // Ссылка на узел-преемник + var prev: ListNode? = null // Ссылка на узел-предшественник } ``` ```ruby title="" -# Класс узла двусвязного списка +### Узел двусвязного списка ### class ListNode - attr_accessor :val # Значение узла - attr_accessor :next # Ссылка на следующий узел - attr_accessor :prev # Ссылка на предыдущий узел + attr_accessor :val # Значение узла + attr_accessor :next # Ссылка на узел-преемник + attr_accessor :prev # Ссылка на узел-предшественник - def initialize(val=0, next_node=nil, prev_node=nil) + ### Конструктор ### + def initialize(val) @val = val - @next = next_node - @prev = prev_node end end ``` diff --git a/ru/codes/snippets/chapter_array_and_linkedlist/list.md b/ru/codes/snippets/chapter_array_and_linkedlist/list.md index 053abf6fa..4bddcc858 100644 --- a/ru/codes/snippets/chapter_array_and_linkedlist/list.md +++ b/ru/codes/snippets/chapter_array_and_linkedlist/list.md @@ -2,25 +2,24 @@ ```python title="list.py" # Инициализация списка # Без начальных значений -nums1: list[int] = [] +empty_nums: list[int] = [] # С начальными значениями nums: list[int] = [1, 3, 2, 5, 4] ``` ```cpp title="list.cpp" /* Инициализация списка */ -// Обратите внимание: в C++ vector соответствует описываемому здесь nums // Без начальных значений -vector nums1; +vector emptyNums; // С начальными значениями -vector nums = { 1, 3, 2, 5, 4 }; +vector nums = {1, 3, 2, 5, 4}; ``` ```java title="list.java" /* Инициализация списка */ // Без начальных значений -List nums1 = new ArrayList<>(); -// С начальными значениями (обратите внимание: элементы массива должны использовать обертку Integer[] вместо int[]) +List emptyNums = new ArrayList<>(); +// С начальными значениями (обратите внимание: массив должен иметь тип Integer[], а не int[], поскольку элементами списка могут быть только объекты класса-обертки Integer) Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); ``` @@ -28,7 +27,7 @@ List nums = new ArrayList<>(Arrays.asList(numbers)); ```csharp title="list.cs" /* Инициализация списка */ // Без начальных значений -List nums1 = []; +List emptyNums = []; // С начальными значениями int[] numbers = [1, 3, 2, 5, 4]; List nums = [.. numbers]; @@ -37,7 +36,7 @@ List nums = [.. numbers]; ```go title="list_test.go" /* Инициализация списка */ // Без начальных значений -nums1 := []int{} +emptyNums := []int{} // С начальными значениями nums := []int{1, 3, 2, 5, 4} ``` @@ -45,7 +44,7 @@ nums := []int{1, 3, 2, 5, 4} ```swift title="list.swift" /* Инициализация списка */ // Без начальных значений -let nums1: [Int] = [] +let emptyNums: [Int] = [] // С начальными значениями var nums = [1, 3, 2, 5, 4] ``` @@ -53,7 +52,7 @@ var nums = [1, 3, 2, 5, 4] ```javascript title="list.js" /* Инициализация списка */ // Без начальных значений -const nums1 = []; +const emptyNums = []; // С начальными значениями const nums = [1, 3, 2, 5, 4]; ``` @@ -61,7 +60,7 @@ const nums = [1, 3, 2, 5, 4]; ```typescript title="list.ts" /* Инициализация списка */ // Без начальных значений -const nums1: number[] = []; +const emptyNums: number[] = []; // С начальными значениями const nums: number[] = [1, 3, 2, 5, 4]; ``` @@ -69,15 +68,15 @@ const nums: number[] = [1, 3, 2, 5, 4]; ```dart title="list.dart" /* Инициализация списка */ // Без начальных значений -List nums1 = []; +List emptyNums = []; // С начальными значениями List nums = [1, 3, 2, 5, 4]; ``` ```rust title="list.rs" -/* Инициализация списка */ +// Инициализация списка // Без начальных значений -let nums1: Vec = Vec::new(); +let empty_nums: Vec = Vec::new(); // С начальными значениями let mut nums: Vec = vec![1, 3, 2, 5, 4]; ``` @@ -89,62 +88,61 @@ let mut nums: Vec = vec![1, 3, 2, 5, 4]; ```kotlin title="list.kt" /* Инициализация списка */ // Без начальных значений -var nums1 = listOf() +val emptyNums = mutableListOf() // С начальными значениями -var numbers = arrayOf(1, 3, 2, 5, 4) -var nums = numbers.toMutableList() +val nums = mutableListOf(1, 3, 2, 5, 4) ``` ```ruby title="list.rb" # Инициализация списка # Без начальных значений -nums1 = [] +empty_nums = [] # С начальными значениями nums = [1, 3, 2, 5, 4] ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20%23%20%D0%91%D0%B5%D0%B7%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D1%85%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B9%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%D0%A1%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%BC%D0%B8%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%D0%BC%D0%B8%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20%23%20%D0%91%D0%B5%D0%B7%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D1%85%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B9%0A%20%20%20%20empty_nums%20%3D%20%5B%5D%0A%20%20%20%20%23%20%D0%A1%20%D0%BD%D0%B0%D1%87%D0%B0%D0%BB%D1%8C%D0%BD%D1%8B%D0%BC%D0%B8%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%D0%BC%D0%B8%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" # Доступ к элементу -num: int = nums[1] # Доступ к элементу по индексу 1 +x: int = nums[1] # Доступ к элементу по индексу 1 # Изменение элемента -nums[1] = 0 # Изменить значение элемента с индексом 1 на 0 +nums[1] = 0 # Изменить значение элемента с индексом 1 на 0 ``` ```cpp title="list.cpp" /* Доступ к элементу */ -int num = nums[1]; // Доступ к элементу по индексу 1 +int num = nums[1]; // Доступ к элементу по индексу 1 /* Изменение элемента */ -nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 ``` ```java title="list.java" /* Доступ к элементу */ -int num = nums.get(1); // Доступ к элементу по индексу 1 +int num = nums.get(1); // Доступ к элементу по индексу 1 /* Изменение элемента */ -nums.set(1, 0); // Изменить значение элемента с индексом 1 на 0 +nums.set(1, 0); // Изменить значение элемента с индексом 1 на 0 ``` ```csharp title="list.cs" /* Доступ к элементу */ -int num = nums[1]; // Доступ к элементу по индексу 1 +int num = nums[1]; // Доступ к элементу по индексу 1 /* Изменение элемента */ -nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 ``` ```go title="list_test.go" /* Доступ к элементу */ -num := nums[1] // Доступ к элементу по индексу 1 +num := nums[1] // Обратиться к элементу по индексу 1 /* Изменение элемента */ -nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 +nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 ``` ```swift title="list.swift" @@ -157,33 +155,34 @@ nums[1] = 0 // Изменить значение элемента с индек ```javascript title="list.js" /* Доступ к элементу */ -const num = nums[1]; // Доступ к элементу по индексу 1 +const num = nums[1]; // Доступ к элементу по индексу 1 /* Изменение элемента */ -nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 ``` ```typescript title="list.ts" /* Доступ к элементу */ -const num: number = nums[1]; // Доступ к элементу по индексу 1 +const num: number = nums[1]; // Доступ к элементу по индексу 1 /* Изменение элемента */ -nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 ``` ```dart title="list.dart" /* Доступ к элементу */ -int num = nums[1]; // Доступ к элементу по индексу 1 +int _num = nums[1]; // Доступ к элементу по индексу 1 /* Изменение элемента */ -nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 ``` ```rust title="list.rs" -/* Доступ к элементу */ -let num: i32 = nums[1]; // Доступ к элементу по индексу 1 -/* Изменение элемента */ -nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 +// Доступ к элементу +let num = nums[1]; // Доступ к элементу по индексу 1 + +// Изменение элемента +nums[1] = 0; // Изменить значение элемента с индексом 1 на 0 ``` ```c title="list.c" @@ -192,109 +191,111 @@ nums[1] = 0; // Изменить значение элемента ```kotlin title="list.kt" /* Доступ к элементу */ -val num = nums[1] // Доступ к элементу по индексу 1 +val num = nums[1] // Доступ к элементу по индексу 1 + /* Изменение элемента */ -nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 +nums[1] = 0 // Изменить значение элемента с индексом 1 на 0 ``` ```ruby title="list.rb" # Доступ к элементу num = nums[1] # Доступ к элементу по индексу 1 + # Изменение элемента nums[1] = 0 # Изменить значение элемента с индексом 1 на 0 ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%D0%94%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D1%83%201%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%BC%D0%B5%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%D0%98%D0%B7%D0%BC%D0%B5%D0%BD%D0%B8%D1%82%D1%8C%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%20%D1%81%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D0%BE%D0%BC%201%20%D0%BD%D0%B0%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%0A%20%20%20%20x%20%3D%20nums%5B1%5D%20%20%23%20%D0%94%D0%BE%D1%81%D1%82%D1%83%D0%BF%20%D0%BA%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%83%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D1%83%201%0A%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%BC%D0%B5%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%D0%98%D0%B7%D0%BC%D0%B5%D0%BD%D0%B8%D1%82%D1%8C%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%20%D1%81%20%D0%B8%D0%BD%D0%B4%D0%B5%D0%BA%D1%81%D0%BE%D0%BC%201%20%D0%BD%D0%B0%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" # Очистить список nums.clear() -# Добавить элементы в конец +# Добавление элемента в конец nums.append(1) nums.append(3) nums.append(2) nums.append(5) nums.append(4) -# Вставить элемент в середину +# Вставка элемента в середину nums.insert(3, 6) # Вставить число 6 по индексу 3 -# Удалить элемент -nums.pop(3) # Удалить элемент по индексу 3 +# Удаление элемента +nums.pop(3) # Удалить элемент по индексу 3 ``` ```cpp title="list.cpp" /* Очистить список */ nums.clear(); -/* Добавить элементы в конец */ +/* Добавление элемента в конец */ nums.push_back(1); nums.push_back(3); nums.push_back(2); nums.push_back(5); nums.push_back(4); -/* Вставить элемент в середину */ -nums.insert(nums.begin() + 3, 6); // Вставить число 6 по индексу 3 +/* Вставка элемента в середину */ +nums.insert(nums.begin() + 3, 6); // Вставить число 6 по индексу 3 -/* Удалить элемент */ -nums.erase(nums.begin() + 3); // Удалить элемент по индексу 3 +/* Удаление элемента */ +nums.erase(nums.begin() + 3); // Удалить элемент по индексу 3 ``` ```java title="list.java" /* Очистить список */ nums.clear(); -/* Добавить элементы в конец */ +/* Добавление элемента в конец */ nums.add(1); nums.add(3); nums.add(2); nums.add(5); nums.add(4); -/* Вставить элемент в середину */ -nums.add(3, 6); // Вставить число 6 по индексу 3 +/* Вставка элемента в середину */ +nums.add(3, 6); // Вставить число 6 по индексу 3 -/* Удалить элемент */ -nums.remove(3); // Удалить элемент по индексу 3 +/* Удаление элемента */ +nums.remove(3); // Удалить элемент по индексу 3 ``` ```csharp title="list.cs" /* Очистить список */ nums.Clear(); -/* Добавить элементы в конец */ +/* Добавление элемента в конец */ nums.Add(1); nums.Add(3); nums.Add(2); nums.Add(5); nums.Add(4); -/* Вставить элемент в середину */ -nums.Insert(3, 6); // Вставить число 6 по индексу 3 +/* Вставка элемента в середину */ +nums.Insert(3, 6); // Вставить число 6 по индексу 3 -/* Удалить элемент */ -nums.RemoveAt(3); // Удалить элемент по индексу 3 +/* Удаление элемента */ +nums.RemoveAt(3); // Удалить элемент по индексу 3 ``` ```go title="list_test.go" /* Очистить список */ nums = nil -/* Добавить элементы в конец */ +/* Добавление элемента в конец */ nums = append(nums, 1) nums = append(nums, 3) nums = append(nums, 2) nums = append(nums, 5) nums = append(nums, 4) -/* Вставить элемент в середину */ +/* Вставка элемента в середину */ nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Вставить число 6 по индексу 3 -/* Удалить элемент */ +/* Удаление элемента */ nums = append(nums[:3], nums[4:]...) // Удалить элемент по индексу 3 ``` @@ -302,17 +303,17 @@ nums = append(nums[:3], nums[4:]...) // Удалить элемент по ин /* Очистить список */ nums.removeAll() -/* Добавить элементы в конец */ +/* Добавление элемента в конец */ nums.append(1) nums.append(3) nums.append(2) nums.append(5) nums.append(4) -/* Вставить элемент в середину */ +/* Вставка элемента в середину */ nums.insert(6, at: 3) // Вставить число 6 по индексу 3 -/* Удалить элемент */ +/* Удаление элемента */ nums.remove(at: 3) // Удалить элемент по индексу 3 ``` @@ -320,72 +321,72 @@ nums.remove(at: 3) // Удалить элемент по индексу 3 /* Очистить список */ nums.length = 0; -/* Добавить элементы в конец */ +/* Добавление элемента в конец */ nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* Вставить элемент в середину */ +/* Вставка элемента в середину */ nums.splice(3, 0, 6); // Вставить число 6 по индексу 3 -/* Удалить элемент */ -nums.splice(3, 1); // Удалить элемент по индексу 3 +/* Удаление элемента */ +nums.splice(3, 1); // Удалить элемент по индексу 3 ``` ```typescript title="list.ts" /* Очистить список */ nums.length = 0; -/* Добавить элементы в конец */ +/* Добавление элемента в конец */ nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* Вставить элемент в середину */ +/* Вставка элемента в середину */ nums.splice(3, 0, 6); // Вставить число 6 по индексу 3 -/* Удалить элемент */ -nums.splice(3, 1); // Удалить элемент по индексу 3 +/* Удаление элемента */ +nums.splice(3, 1); // Удалить элемент по индексу 3 ``` ```dart title="list.dart" /* Очистить список */ nums.clear(); -/* Добавить элементы в конец */ +/* Добавление элемента в конец */ nums.add(1); nums.add(3); nums.add(2); nums.add(5); nums.add(4); -/* Вставить элемент в середину */ +/* Вставка элемента в середину */ nums.insert(3, 6); // Вставить число 6 по индексу 3 -/* Удалить элемент */ +/* Удаление элемента */ nums.removeAt(3); // Удалить элемент по индексу 3 ``` ```rust title="list.rs" -/* Очистить список */ +// Очистить список nums.clear(); -/* Добавить элементы в конец */ +// Добавление элемента в конец nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* Вставить элемент в середину */ -nums.insert(3, 6); // Вставить число 6 по индексу 3 +// Вставка элемента в середину +nums.insert(3, 6); // Вставить число 6 по индексу 3 -/* Удалить элемент */ -nums.remove(3); // Удалить элемент по индексу 3 +// Удаление элемента +nums.remove(3); // Удалить элемент по индексу 3 ``` ```c title="list.c" @@ -394,37 +395,37 @@ nums.remove(3); // Удалить элемент по индексу 3 ```kotlin title="list.kt" /* Очистить список */ -nums.clear(); +nums.clear() -/* Добавить элементы в конец */ -nums.add(1); -nums.add(3); -nums.add(2); -nums.add(5); -nums.add(4); +/* Добавление элемента в конец */ +nums.add(1) +nums.add(3) +nums.add(2) +nums.add(5) +nums.add(4) -/* Вставить элемент в середину */ -nums.add(3, 6); // Вставить число 6 по индексу 3 +/* Вставка элемента в середину */ +nums.add(3, 6) // Вставить число 6 по индексу 3 -/* Удалить элемент */ -nums.removeAt(3); // Удалить элемент по индексу 3 +/* Удаление элемента */ +nums.removeAt(3) // Удалить элемент по индексу 3 ``` ```ruby title="list.rb" # Очистить список nums.clear -# Добавить элементы в конец +# Добавление элемента в конец nums << 1 nums << 3 nums << 2 nums << 5 nums << 4 -# Вставить элемент в середину +# Вставка элемента в середину nums.insert(3, 6) # Вставить число 6 по индексу 3 -# Удалить элемент +# Удаление элемента nums.delete_at(3) # Удалить элемент по индексу 3 ``` @@ -433,138 +434,138 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 ```python title="list.py" -# Обход списка по индексам +# Обходить список по индексам count = 0 for i in range(len(nums)): count += nums[i] -# Прямой обход элементов списка +# Непосредственно обходить элементы списка for num in nums: count += num ``` ```cpp title="list.cpp" -/* Обход списка по индексам */ +/* Обходить список по индексам */ int count = 0; for (int i = 0; i < nums.size(); i++) { count += nums[i]; } -/* Прямой обход элементов списка */ +/* Непосредственно обходить элементы списка */ count = 0; -for (int num : nums) { - count += num; +for (int x : nums) { + count += x; } ``` ```java title="list.java" -/* Обход списка по индексам */ +/* Обходить список по индексам */ int count = 0; for (int i = 0; i < nums.size(); i++) { count += nums.get(i); } -/* Прямой обход элементов списка */ -for (int num : nums) { - count += num; +/* Непосредственно обходить элементы списка */ +for (int x : nums) { + count += x; } ``` ```csharp title="list.cs" -/* Обход списка по индексам */ +/* Обходить список по индексам */ int count = 0; for (int i = 0; i < nums.Count; i++) { count += nums[i]; } -/* Прямой обход элементов списка */ +/* Непосредственно обходить элементы списка */ count = 0; -foreach (int num in nums) { - count += num; +foreach (int x in nums) { + count += x; } ``` ```go title="list_test.go" -/* Обход списка по индексам */ +/* Обходить список по индексам */ count := 0 for i := 0; i < len(nums); i++ { count += nums[i] } -/* Прямой обход элементов списка */ +/* Непосредственно обходить элементы списка */ count = 0 -for _, num := range nums { - count += num +for _, x := range nums { + count += x } ``` ```swift title="list.swift" -/* Обход списка по индексам */ +/* Обходить список по индексам */ var count = 0 for i in nums.indices { count += nums[i] } -/* Прямой обход элементов списка */ +/* Непосредственно обходить элементы списка */ count = 0 -for num in nums { - count += num +for x in nums { + count += x } ``` ```javascript title="list.js" -/* Обход списка по индексам */ +/* Обходить список по индексам */ let count = 0; for (let i = 0; i < nums.length; i++) { count += nums[i]; } -/* Прямой обход элементов списка */ +/* Непосредственно обходить элементы списка */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` ```typescript title="list.ts" -/* Обход списка по индексам */ +/* Обходить список по индексам */ let count = 0; for (let i = 0; i < nums.length; i++) { count += nums[i]; } -/* Прямой обход элементов списка */ +/* Непосредственно обходить элементы списка */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` ```dart title="list.dart" -/* Обход списка по индексам */ +/* Обходить список по индексам */ int count = 0; for (var i = 0; i < nums.length; i++) { - count += nums[i]; + count += nums[i]; } -/* Прямой обход элементов списка */ +/* Непосредственно обходить элементы списка */ count = 0; -for (var num in nums) { - count += num; +for (var x in nums) { + count += x; } ``` ```rust title="list.rs" -// Обход списка по индексам +// Обходить список по индексам let mut _count = 0; for i in 0..nums.len() { _count += nums[i]; } -// Прямой обход элементов списка +// Непосредственно обходить элементы списка _count = 0; -for num in &nums { - _count += num; +for x in &nums { + _count += x; } ``` @@ -573,29 +574,29 @@ for num in &nums { ``` ```kotlin title="list.kt" -/* Обход списка по индексам */ +/* Обходить список по индексам */ var count = 0 for (i in nums.indices) { count += nums[i] } -/* Прямой обход элементов списка */ -for (num in nums) { - count += num +/* Непосредственно обходить элементы списка */ +for (j in nums) { + count += j } ``` ```ruby title="list.rb" -# Обход списка по индексам +# Обходить список по индексам count = 0 for i in 0...nums.length - count += nums[i] + count += nums[i] end -# Прямой обход элементов списка +# Непосредственно обходить элементы списка count = 0 -for num in nums - count += num +nums.each do |x| + count += x end ``` @@ -604,64 +605,64 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 ```python title="list.py" -# Конкатенация двух списков -nums1: list[int] = [6, 8, 7, 10, 9] +# Объединить два списка +nums1 = [6, 8, 7, 10, 9] nums += nums1 # Присоединить список nums1 к концу nums ``` ```cpp title="list.cpp" -/* Конкатенация двух списков */ -vector nums1 = { 6, 8, 7, 10, 9 }; +/* Объединить два списка */ +vector nums1 = {6, 8, 7, 10, 9}; // Присоединить список nums1 к концу nums nums.insert(nums.end(), nums1.begin(), nums1.end()); ``` ```java title="list.java" -/* Конкатенация двух списков */ +/* Объединить два списка */ List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); -nums.addAll(nums1); // Присоединить список nums1 к концу nums +nums.addAll(nums1); // Присоединить список nums1 к концу nums ``` ```csharp title="list.cs" -/* Конкатенация двух списков */ +/* Объединить два списка */ List nums1 = [6, 8, 7, 10, 9]; -nums.AddRange(nums1); // Присоединить список nums1 к концу nums +nums.AddRange(nums1); // Присоединить список nums1 к концу nums ``` ```go title="list_test.go" -/* Конкатенация двух списков */ +/* Объединить два списка */ nums1 := []int{6, 8, 7, 10, 9} -nums = append(nums, nums1...) // Присоединить список nums1 к концу nums +nums = append(nums, nums1...) // Присоединить список nums1 после nums ``` ```swift title="list.swift" -/* Конкатенация двух списков */ +/* Объединить два списка */ let nums1 = [6, 8, 7, 10, 9] nums.append(contentsOf: nums1) // Присоединить список nums1 к концу nums ``` ```javascript title="list.js" -/* Конкатенация двух списков */ +/* Объединить два списка */ const nums1 = [6, 8, 7, 10, 9]; -nums.push(...nums1); // Присоединить список nums1 к концу nums +nums.push(...nums1); // Присоединить список nums1 к концу nums ``` ```typescript title="list.ts" -/* Конкатенация двух списков */ +/* Объединить два списка */ const nums1: number[] = [6, 8, 7, 10, 9]; -nums.push(...nums1); // Присоединить список nums1 к концу nums +nums.push(...nums1); // Присоединить список nums1 к концу nums ``` ```dart title="list.dart" -/* Конкатенация двух списков */ +/* Объединить два списка */ List nums1 = [6, 8, 7, 10, 9]; -nums.addAll(nums1); // Присоединить список nums1 к концу nums +nums.addAll(nums1); // Присоединить список nums1 к концу nums ``` ```rust title="list.rs" -/* Конкатенация двух списков */ -let nums1: Vec = vec![6, 8, 7, 10, 9]; -nums.extend(nums1); +// Объединить два списка +let mut nums1 = vec![6, 8, 7, 10, 9]; +nums.append(&mut nums1); // append перемещает элементы nums1, после чего nums1 становится пустым ``` ```c title="list.c" @@ -669,13 +670,13 @@ nums.extend(nums1); ``` ```kotlin title="list.kt" -/* Конкатенация двух списков */ -val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() -nums.addAll(nums1) // Присоединить список nums1 к концу nums +/* Объединить два списка */ +val nums1 = mutableListOf(6, 8, 7, 10, 9) +nums.addAll(nums1) // Присоединить список nums1 к концу nums ``` ```ruby title="list.rb" -# Конкатенация двух списков +# Объединить два списка nums1 = [6, 8, 7, 10, 9] nums += nums1 ``` @@ -691,22 +692,22 @@ nums.sort() # После сортировки элементы списка и ```cpp title="list.cpp" /* Отсортировать список */ -sort(nums.begin(), nums.end()); // После сортировки элементы списка идут по возрастанию +sort(nums.begin(), nums.end()); // После сортировки элементы списка идут по возрастанию ``` ```java title="list.java" /* Отсортировать список */ -Collections.sort(nums); // После сортировки элементы списка идут по возрастанию +Collections.sort(nums); // После сортировки элементы списка идут по возрастанию ``` ```csharp title="list.cs" /* Отсортировать список */ -nums.Sort(); // После сортировки элементы списка идут по возрастанию +nums.Sort(); // После сортировки элементы списка располагаются по возрастанию ``` ```go title="list_test.go" /* Отсортировать список */ -sort.Ints(nums) // После сортировки элементы списка идут по возрастанию +sort.Ints(nums) // После сортировки элементы списка располагаются по возрастанию ``` ```swift title="list.swift" @@ -716,12 +717,12 @@ nums.sort() // После сортировки элементы списка и ```javascript title="list.js" /* Отсортировать список */ -nums.sort((a, b) => a - b); // После сортировки элементы списка идут по возрастанию +nums.sort((a, b) => a - b); // После сортировки элементы списка идут по возрастанию ``` ```typescript title="list.ts" /* Отсортировать список */ -nums.sort((a, b) => a - b); // После сортировки элементы списка идут по возрастанию +nums.sort((a, b) => a - b); // После сортировки элементы списка идут по возрастанию ``` ```dart title="list.dart" @@ -730,7 +731,7 @@ nums.sort(); // После сортировки элементы списка и ``` ```rust title="list.rs" -/* Отсортировать список */ +// Отсортировать список nums.sort(); // После сортировки элементы списка идут по возрастанию ``` diff --git a/ru/codes/snippets/chapter_hashing/hash_algorithm.md b/ru/codes/snippets/chapter_hashing/hash_algorithm.md index 716034d3d..f95a2b1dc 100644 --- a/ru/codes/snippets/chapter_hashing/hash_algorithm.md +++ b/ru/codes/snippets/chapter_hashing/hash_algorithm.md @@ -2,100 +2,122 @@ ```python title="built_in_hash.py" num = 3 hash_num = hash(num) -# Хеш-значение целого числа 3 равно 3 +print(f"Хеш-значение целого числа {num} = {hash_num}") +# Хеш-значение целого числа 3 = 3 bol = True hash_bol = hash(bol) -# Хеш-значение булевого значения True равно 1 +print(f"Хеш-значение булева значения {bol} = {hash_bol}") +# Хеш-значение булева значения True = 1 dec = 3.14159 hash_dec = hash(dec) -# Хеш-значение числа 3.14159 равно 326484311674566659 +print(f"Хеш-значение десятичного числа {dec} = {hash_dec}") +# Хеш-значение десятичного числа 3.14159 = 326484311674566659 str = "Hello Algo" hash_str = hash(str) -# Хеш-значение строки "Hello Algo" равно 4617003410720528961 +print(f"Хеш-значение строки «{str}» = {hash_str}") +# Хеш-значение строки «Hello Algo» = 4617003410720528961 tup = (12836, "Сяо Ха") hash_tup = hash(tup) -# Хеш-значение кортежа (12836, "Сяо Ха") равно 1029005403108185979 +print(f"Хеш-значение кортежа {tup} = {hash_tup}") +# Хеш-значение кортежа (12836, 'Сяо Ха') = 1029005403108185979 obj = ListNode(0) hash_obj = hash(obj) -# Хеш-значение объекта узла равно 274267521 +print(f"Хеш-значение объекта узла {obj} = {hash_obj}") +# Хеш-значение объекта узла = 274267521 ``` ```cpp title="built_in_hash.cpp" int num = 3; size_t hashNum = hash()(num); -// Хеш-значение целого числа 3 равно 3 +cout << "Хеш-значение целого числа " << num << " = " << hashNum << "\n"; +// Хеш-значение целого числа 3 = 3 bool bol = true; size_t hashBol = hash()(bol); -// Хеш-значение булевого значения 1 равно 1 +cout << "Хеш-значение булева значения " << bol << " = " << hashBol << "\n"; +// Хеш-значение булева значения 1 = 1 double dec = 3.14159; size_t hashDec = hash()(dec); -// Хеш-значение числа 3.14159 равно 4614256650576692846 +cout << "Хеш-значение десятичного числа " << dec << " = " << hashDec << "\n"; +// Хеш-значение десятичного числа 3.14159 = 4614256650576692846 string str = "Hello Algo"; size_t hashStr = hash()(str); -// Хеш-значение строки "Hello Algo" равно 15466937326284535026 +cout << "Хеш-значение строки «" << str << "» = " << hashStr << "\n"; +// Хеш-значение строки «Hello Algo» = 15466937326284535026 // В C++ встроенный std::hash() предоставляет вычисление хеша только для базовых типов данных -// Для массивов и объектов хеш-значение обычно приходится реализовывать самостоятельно +// Вычисление хеша для массивов и объектов нужно реализовывать самостоятельно ``` ```java title="built_in_hash.java" int num = 3; int hashNum = Integer.hashCode(num); -// Хеш-значение целого числа 3 равно 3 +System.out.println("Хеш-значение целого числа " + num + " = " + hashNum); +// Хеш-значение целого числа 3 = 3 boolean bol = true; int hashBol = Boolean.hashCode(bol); -// Хеш-значение булевого значения true равно 1231 +System.out.println("Хеш-значение булева значения " + bol + " = " + hashBol); +// Хеш-значение булева значения true = 1231 double dec = 3.14159; int hashDec = Double.hashCode(dec); -// Хеш-значение числа 3.14159 равно -1340954729 +System.out.println("Хеш-значение десятичного числа " + dec + " = " + hashDec); +// Хеш-значение десятичного числа 3.14159 = -1340954729 String str = "Hello Algo"; int hashStr = str.hashCode(); -// Хеш-значение строки "Hello Algo" равно -727081396 +System.out.println("Хеш-значение строки «" + str + "» = " + hashStr); +// Хеш-значение строки «Hello Algo» = 387159329 Object[] arr = { 12836, "Сяо Ха" }; -int hashTup = Arrays.hashCode(arr); -// Хеш-значение массива [12836, Сяо Ха] равно 1151158 +int hashArr = Arrays.hashCode(arr); +System.out.println("Хеш-значение массива " + Arrays.toString(arr) + " = " + hashArr); +// Хеш-значение массива [12836, Сяо Ха] = 1247701816 ListNode obj = new ListNode(0); int hashObj = obj.hashCode(); -// Хеш-значение объекта узла utils.ListNode@7dc5e7b4 равно 2110121908 +System.out.println("Хеш-значение объекта узла " + obj + " = " + hashObj); +// Хеш-значение объекта узла utils.ListNode@7dc5e7b4 = 2110121908 ``` ```csharp title="built_in_hash.cs" int num = 3; int hashNum = num.GetHashCode(); -// Хеш-значение целого числа 3 равно 3; +Console.WriteLine("Хеш-значение целого числа " + num + " = " + hashNum); +// Хеш-значение целого числа 3 = 3 bool bol = true; int hashBol = bol.GetHashCode(); -// Хеш-значение булевого значения true равно 1; +Console.WriteLine("Хеш-значение булева значения " + bol + " = " + hashBol); +// Хеш-значение булева значения True = 1 double dec = 3.14159; int hashDec = dec.GetHashCode(); -// Хеш-значение числа 3.14159 равно -1340954729; +Console.WriteLine("Хеш-значение десятичного числа " + dec + " = " + hashDec); +// Хеш-значение десятичного числа 3.14159 = -1340954729 string str = "Hello Algo"; int hashStr = str.GetHashCode(); -// Хеш-значение строки "Hello Algo" равно -586107568; +Console.WriteLine("Хеш-значение строки «" + str + "» = " + hashStr); +// Хеш-значение строки «Hello Algo» = -586107568 object[] arr = [12836, "Сяо Ха"]; -int hashTup = arr.GetHashCode(); -// Хеш-значение массива [12836, Сяо Ха] равно 42931033; +int hashArr = arr.GetHashCode(); +Console.WriteLine("Хеш-значение массива [" + string.Join(", ", arr) + "] = " + hashArr); +// Хеш-значение массива [12836, Сяо Ха] = 42931033 ListNode obj = new(0); int hashObj = obj.GetHashCode(); -// Хеш-значение объекта узла 0 равно 39053774; +Console.WriteLine("Хеш-значение объекта узла " + obj + " = " + hashObj); +// Хеш-значение объекта узла 0 = 39053774 ``` ```go title="built_in_hash.go" @@ -105,27 +127,33 @@ int hashObj = obj.GetHashCode(); ```swift title="built_in_hash.swift" let num = 3 let hashNum = num.hashValue -// Хеш-значение целого числа 3 равно 9047044699613009734 +print("Хеш-значение целого числа \(num) = \(hashNum)") +// Хеш-значение целого числа 3 = 9047044699613009734 let bol = true let hashBol = bol.hashValue -// Хеш-значение булевого значения true равно -4431640247352757451 +print("Хеш-значение булева значения \(bol) = \(hashBol)") +// Хеш-значение булева значения true = -4431640247352757451 let dec = 3.14159 let hashDec = dec.hashValue -// Хеш-значение числа 3.14159 равно -2465384235396674631 +print("Хеш-значение десятичного числа \(dec) = \(hashDec)") +// Хеш-значение десятичного числа 3.14159 = -2465384235396674631 let str = "Hello Algo" let hashStr = str.hashValue -// Хеш-значение строки "Hello Algo" равно -7850626797806988787 +print("Хеш-значение строки «\(str)» = \(hashStr)") +// Хеш-значение строки «Hello Algo» = -7850626797806988787 let arr = [AnyHashable(12836), AnyHashable("Сяо Ха")] -let hashTup = arr.hashValue -// Хеш-значение массива [AnyHashable(12836), AnyHashable("Сяо Ха")] равно -2308633508154532996 +let hashArr = arr.hashValue +print("Хеш-значение массива \(arr) = \(hashArr)") +// Хеш-значение массива [AnyHashable(12836), AnyHashable("Сяо Ха")] = -2308633508154532996 let obj = ListNode(x: 0) let hashObj = obj.hashValue -// Хеш-значение объекта узла utils.ListNode равно -2434780518035996159 +print("Хеш-значение объекта узла \(obj) = \(hashObj)") +// Хеш-значение объекта узла utils.ListNode = -2434780518035996159 ``` ```javascript title="built_in_hash.js" @@ -139,27 +167,33 @@ let hashObj = obj.hashValue ```dart title="built_in_hash.dart" int num = 3; int hashNum = num.hashCode; -// Хеш-значение целого числа 3 равно 34803 +print("Хеш-значение целого числа $num = $hashNum"); +// Хеш-значение целого числа 3 = 34803 bool bol = true; int hashBol = bol.hashCode; -// Хеш-значение булевого значения true равно 1231 +print("Хеш-значение булева значения $bol = $hashBol"); +// Хеш-значение булева значения true = 1231 double dec = 3.14159; int hashDec = dec.hashCode; -// Хеш-значение числа 3.14159 равно 2570631074981783 +print("Хеш-значение десятичного числа $dec = $hashDec"); +// Хеш-значение десятичного числа 3.14159 = 2570631074981783 String str = "Hello Algo"; int hashStr = str.hashCode; -// Хеш-значение строки "Hello Algo" равно 468167534 +print("Хеш-значение строки «$str» = $hashStr"); +// Хеш-значение строки «Hello Algo» = 335226759 List arr = [12836, "Сяо Ха"]; int hashArr = arr.hashCode; -// Хеш-значение массива [12836, Сяо Ха] равно 976512528 +print("Хеш-значение массива $arr = $hashArr"); +// Хеш-значение массива [12836, Сяо Ха] = 976512528 -ListNode obj = new ListNode(0); +ListNode obj = ListNode(0); int hashObj = obj.hashCode; -// Хеш-значение объекта Instance of 'ListNode' равно 1033450432 +print("Хеш-значение объекта узла $obj = $hashObj"); +// Хеш-значение объекта узла Instance of 'ListNode' = 1033450432 ``` ```rust title="built_in_hash.rs" @@ -170,37 +204,43 @@ let num = 3; let mut num_hasher = DefaultHasher::new(); num.hash(&mut num_hasher); let hash_num = num_hasher.finish(); -// Хеш-значение целого числа 3 равно 568126464209439262 +println!("Хеш-значение целого числа {} = {}", num, hash_num); +// Хеш-значение целого числа 3 = 568126464209439262 let bol = true; let mut bol_hasher = DefaultHasher::new(); bol.hash(&mut bol_hasher); let hash_bol = bol_hasher.finish(); -// Хеш-значение булевого значения true равно 4952851536318644461 +println!("Хеш-значение булева значения {} = {}", bol, hash_bol); +// Хеш-значение булева значения true = 4952851536318644461 let dec: f32 = 3.14159; let mut dec_hasher = DefaultHasher::new(); dec.to_bits().hash(&mut dec_hasher); let hash_dec = dec_hasher.finish(); -// Хеш-значение числа 3.14159 равно 2566941990314602357 +println!("Хеш-значение десятичного числа {} = {}", dec, hash_dec); +// Хеш-значение десятичного числа 3.14159 = 2566941990314602357 let str = "Hello Algo"; let mut str_hasher = DefaultHasher::new(); str.hash(&mut str_hasher); let hash_str = str_hasher.finish(); -// Хеш-значение строки "Hello Algo" равно 16092673739211250988 +println!("Хеш-значение строки «{}» = {}", str, hash_str); +// Хеш-значение строки «Hello Algo» = 17488118421444754255 -let arr = (&12836, &"Сяо Ха"); +let tup = (&12836, &"Сяо Ха"); let mut tup_hasher = DefaultHasher::new(); -arr.hash(&mut tup_hasher); +tup.hash(&mut tup_hasher); let hash_tup = tup_hasher.finish(); -// Хеш-значение кортежа (12836, "Сяо Ха") равно 1885128010422702749 +println!("Хеш-значение кортежа {:?} = {}", tup, hash_tup); +// Хеш-значение кортежа (12836, "Сяо Ха") = 11477145348646942370 let node = ListNode::new(42); -let mut hasher = DefaultHasher::new(); -node.borrow().val.hash(&mut hasher); -let hash = hasher.finish(); -// Хеш-значение объекта RefCell { value: ListNode { val: 42, next: None } } равно 15387811073369036852 +let mut node_hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut node_hasher); +let hash_node = node_hasher.finish(); +println!("Хеш-значение объекта узла {:?} = {}", node, hash_node); +// Хеш-значение объекта узла RefCell { value: ListNode { val: 42, next: None } } = 15387811073369036852 ``` ```c title="built_in_hash.c" @@ -210,54 +250,66 @@ let hash = hasher.finish(); ```kotlin title="built_in_hash.kt" val num = 3 val hashNum = num.hashCode() -// Хеш-значение целого числа 3 равно 3 +println("Хеш-значение целого числа $num = $hashNum") +// Хеш-значение целого числа 3 = 3 val bol = true val hashBol = bol.hashCode() -// Хеш-значение булевого значения true равно 1231 +println("Хеш-значение булева значения $bol = $hashBol") +// Хеш-значение булева значения true = 1231 val dec = 3.14159 val hashDec = dec.hashCode() -// Хеш-значение числа 3.14159 равно -1340954729 +println("Хеш-значение десятичного числа $dec = $hashDec") +// Хеш-значение десятичного числа 3.14159 = -1340954729 val str = "Hello Algo" val hashStr = str.hashCode() -// Хеш-значение строки "Hello Algo" равно -727081396 +println("Хеш-значение строки «$str» = $hashStr") +// Хеш-значение строки «Hello Algo» = 387159329 val arr = arrayOf(12836, "Сяо Ха") -val hashTup = arr.hashCode() -// Хеш-значение массива [12836, Сяо Ха] равно 189568618 +val hashArr = arr.contentHashCode() +println("Хеш-значение массива ${arr.contentToString()} = $hashArr") +// Хеш-значение массива [12836, Сяо Ха] = 1247701816 val obj = ListNode(0) val hashObj = obj.hashCode() -// Хеш-значение объекта узла utils.ListNode@1d81eb93 равно 495053715 +println("Хеш-значение объекта узла $obj = $hashObj") +// Хеш-значение объекта узла utils.ListNode@1d81eb93 = 495053715 ``` ```ruby title="built_in_hash.rb" num = 3 hash_num = num.hash -# Хеш-значение целого числа 3 равно -4385856518450339636 +puts "Хеш-значение целого числа #{num} = #{hash_num}" +# Хеш-значение целого числа 3 = -4385856518450339636 bol = true hash_bol = bol.hash -# Хеш-значение булевого значения true равно -1617938112149317027 +puts "Хеш-значение булева значения #{bol} = #{hash_bol}" +# Хеш-значение булева значения true = -1617938112149317027 dec = 3.14159 hash_dec = dec.hash -# Хеш-значение числа 3.14159 равно -1479186995943067893 +puts "Хеш-значение десятичного числа #{dec} = #{hash_dec}" +# Хеш-значение десятичного числа 3.14159 = -1479186995943067893 str = "Hello Algo" hash_str = str.hash -# Хеш-значение строки "Hello Algo" равно -4075943250025831763 +puts "Хеш-значение строки «#{str}» = #{hash_str}" +# Хеш-значение строки «Hello Algo» = -4075943250025831763 -tup = [12836, 'Сяо Ха'] -hash_tup = tup.hash -# Хеш-значение кортежа (12836, 'Сяо Ха') равно 1999544809202288822 +arr = [12836, 'Сяо Ха'] +hash_arr = arr.hash +puts "Хеш-значение массива #{arr} = #{hash_arr}" +# Хеш-значение массива [12836, "Сяо Ха"] = 1999544809202288822 obj = ListNode.new(0) hash_obj = obj.hash -# Хеш-значение объекта # равно 4302940560806366381 +puts "Хеш-значение объекта узла #{obj} = #{hash_obj}" +# Хеш-значение объекта узла # = 4302940560806366381 ``` -https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D1%83%D0%B7%D0%B5%D0%BB%D0%BA%D0%BB%D0%B0%D1%81%D1%81%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D1%81%D0%BB%D0%B5%D0%B4%D1%83%D1%8E%D1%89%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%86%D0%B5%D0%BB%D0%BE%D0%B3%D0%BE%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%203%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%B1%D1%83%D0%BB%D0%B5%D0%B2%D0%B0%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20True%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%203.14159%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20Algo%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8%20%22Hello%20Algo%22%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BA%D0%BE%D1%80%D1%82%D0%B5%D0%B6%D0%B0%20%2812836%2C%20%27%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%27%29%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%B0%20%D1%83%D0%B7%D0%BB%D0%B0%20%3CListNode%20object%20at%200x1058fd810%3E%20%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%D1%81%D0%B2%D1%8F%D0%B7%D0%BD%D1%8B%D0%B9%20%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D1%83%D0%B7%D0%B5%D0%BB%D0%BA%D0%BB%D0%B0%D1%81%D1%81%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D1%81%D0%BB%D0%B5%D0%B4%D1%83%D1%8E%D1%89%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20print%28f%22%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%86%D0%B5%D0%BB%D0%BE%D0%B3%D0%BE%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%20%7Bnum%7D%20%3D%20%7Bhash_num%7D%22%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%86%D0%B5%D0%BB%D0%BE%D0%B3%D0%BE%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%203%20%3D%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20print%28f%22%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%B1%D1%83%D0%BB%D0%B5%D0%B2%D0%B0%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20%7Bbol%7D%20%3D%20%7Bhash_bol%7D%22%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%B1%D1%83%D0%BB%D0%B5%D0%B2%D0%B0%20%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D1%8F%20True%20%3D%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20print%28f%22%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%B4%D0%B5%D1%81%D1%8F%D1%82%D0%B8%D1%87%D0%BD%D0%BE%D0%B3%D0%BE%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%20%7Bdec%7D%20%3D%20%7Bhash_dec%7D%22%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%B4%D0%B5%D1%81%D1%8F%D1%82%D0%B8%D1%87%D0%BD%D0%BE%D0%B3%D0%BE%20%D1%87%D0%B8%D1%81%D0%BB%D0%B0%203.14159%20%3D%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20Algo%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20print%28f%22%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8%20%C2%AB%7Bstr%7D%C2%BB%20%3D%20%7Bhash_str%7D%22%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8%20%C2%ABHello%20Algo%C2%BB%20%3D%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20print%28f%22%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BA%D0%BE%D1%80%D1%82%D0%B5%D0%B6%D0%B0%20%7Btup%7D%20%3D%20%7Bhash_tup%7D%22%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BA%D0%BE%D1%80%D1%82%D0%B5%D0%B6%D0%B0%20%2812836%2C%20%27%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%27%29%20%3D%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20print%28f%22%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%B0%20%D1%83%D0%B7%D0%BB%D0%B0%20%7Bobj%7D%20%3D%20%7Bhash_obj%7D%22%29%0A%20%20%20%20%23%20%D0%A5%D0%B5%D1%88-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%B0%20%D1%83%D0%B7%D0%BB%D0%B0%20%3Cmodules.list_node.ListNode%20object%20at%200x1058fd810%3E%20%3D%20274267521%0A&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_hashing/hash_map.md b/ru/codes/snippets/chapter_hashing/hash_map.md index 80eb2476a..8d7da75a1 100644 --- a/ru/codes/snippets/chapter_hashing/hash_map.md +++ b/ru/codes/snippets/chapter_hashing/hash_map.md @@ -1,10 +1,10 @@ ```python title="hash_map.py" # Инициализация хеш-таблицы -hmap: dict = {} +hmap = dict[int, str]() # Операция добавления -# Добавить пару ключ-значение (key, value) в хеш-таблицу +# Добавить пару (key, value) в хеш-таблицу hmap[12836] = "Сяо Ха" hmap[15937] = "Сяо Ло" hmap[16750] = "Сяо Суань" @@ -12,11 +12,11 @@ hmap[13276] = "Сяо Фа" hmap[10583] = "Сяо Я" # Операция поиска -# Передать в хеш-таблицу ключ key и получить значение value +# Передать ключ key в хеш-таблицу и получить значение value name: str = hmap[15937] # Операция удаления -# Удалить пару ключ-значение (key, value) из хеш-таблицы +# Удалить пару (key, value) из хеш-таблицы hmap.pop(10583) ``` @@ -25,7 +25,7 @@ hmap.pop(10583) unordered_map map; /* Операция добавления */ -// Добавить пару ключ-значение (key, value) в хеш-таблицу +// Добавить пару (key, value) в хеш-таблицу map[12836] = "Сяо Ха"; map[15937] = "Сяо Ло"; map[16750] = "Сяо Суань"; @@ -33,11 +33,11 @@ map[13276] = "Сяо Фа"; map[10583] = "Сяо Я"; /* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value +// Ввести в хеш-таблицу ключ key и получить значение value string name = map[15937]; /* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы +// Удалить пару (key, value) из хеш-таблицы map.erase(10583); ``` @@ -46,7 +46,7 @@ map.erase(10583); Map map = new HashMap<>(); /* Операция добавления */ -// Добавить пару ключ-значение (key, value) в хеш-таблицу +// Добавить пару (key, value) в хеш-таблицу map.put(12836, "Сяо Ха"); map.put(15937, "Сяо Ло"); map.put(16750, "Сяо Суань"); @@ -54,11 +54,11 @@ map.put(13276, "Сяо Фа"); map.put(10583, "Сяо Я"); /* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value +// Ввести в хеш-таблицу ключ key и получить значение value String name = map.get(15937); /* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы +// Удалить пару (key, value) из хеш-таблицы map.remove(10583); ``` @@ -66,7 +66,7 @@ map.remove(10583); /* Инициализация хеш-таблицы */ Dictionary map = new() { /* Операция добавления */ - // Добавить пару ключ-значение (key, value) в хеш-таблицу + // Добавить пару (key, value) в хеш-таблицу { 12836, "Сяо Ха" }, { 15937, "Сяо Ло" }, { 16750, "Сяо Суань" }, @@ -75,11 +75,11 @@ Dictionary map = new() { }; /* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value +// Ввести в хеш-таблицу ключ key и получить значение value string name = map[15937]; /* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы +// Удалить пару (key, value) из хеш-таблицы map.Remove(10583); ``` @@ -88,7 +88,7 @@ map.Remove(10583); hmap := make(map[int]string) /* Операция добавления */ -// Добавить пару ключ-значение (key, value) в хеш-таблицу +// Добавить пару (key, value) в хеш-таблицу hmap[12836] = "Сяо Ха" hmap[15937] = "Сяо Ло" hmap[16750] = "Сяо Суань" @@ -96,11 +96,11 @@ hmap[13276] = "Сяо Фа" hmap[10583] = "Сяо Я" /* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value +// Ввести в хеш-таблицу ключ key и получить значение value name := hmap[15937] /* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы +// Удалить пару (key, value) из хеш-таблицы delete(hmap, 10583) ``` @@ -109,7 +109,7 @@ delete(hmap, 10583) var map: [Int: String] = [:] /* Операция добавления */ -// Добавить пару ключ-значение (key, value) в хеш-таблицу +// Добавить пару (key, value) в хеш-таблицу map[12836] = "Сяо Ха" map[15937] = "Сяо Ло" map[16750] = "Сяо Суань" @@ -117,19 +117,20 @@ map[13276] = "Сяо Фа" map[10583] = "Сяо Я" /* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value +// Ввести в хеш-таблицу ключ key и получить значение value let name = map[15937]! /* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы +// Удалить пару (key, value) из хеш-таблицы map.removeValue(forKey: 10583) ``` ```javascript title="hash_map.js" /* Инициализация хеш-таблицы */ const map = new Map(); + /* Операция добавления */ -// Добавить пару ключ-значение (key, value) в хеш-таблицу +// Добавить пару (key, value) в хеш-таблицу map.set(12836, 'Сяо Ха'); map.set(15937, 'Сяо Ло'); map.set(16750, 'Сяо Суань'); @@ -137,45 +138,41 @@ map.set(13276, 'Сяо Фа'); map.set(10583, 'Сяо Я'); /* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value +// Ввести в хеш-таблицу ключ key и получить значение value let name = map.get(15937); /* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы +// Удалить пару (key, value) из хеш-таблицы map.delete(10583); ``` ```typescript title="hash_map.ts" /* Инициализация хеш-таблицы */ const map = new Map(); + /* Операция добавления */ -// Добавить пару ключ-значение (key, value) в хеш-таблицу +// Добавить пару (key, value) в хеш-таблицу map.set(12836, 'Сяо Ха'); map.set(15937, 'Сяо Ло'); map.set(16750, 'Сяо Суань'); map.set(13276, 'Сяо Фа'); map.set(10583, 'Сяо Я'); -console.info('\nПосле добавления хеш-таблица имеет вид\nKey -> Value'); -console.info(map); /* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value +// Ввести в хеш-таблицу ключ key и получить значение value let name = map.get(15937); -console.info('\nПо номеру 15937 найдено имя ' + name); /* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы +// Удалить пару (key, value) из хеш-таблицы map.delete(10583); -console.info('\nПосле удаления 10583 хеш-таблица имеет вид\nKey -> Value'); -console.info(map); ``` ```dart title="hash_map.dart" /* Инициализация хеш-таблицы */ -Map map = {}; +final Map map = {}; /* Операция добавления */ -// Добавить пару ключ-значение (key, value) в хеш-таблицу +// Добавить пару (key, value) в хеш-таблицу map[12836] = "Сяо Ха"; map[15937] = "Сяо Ло"; map[16750] = "Сяо Суань"; @@ -183,35 +180,35 @@ map[13276] = "Сяо Фа"; map[10583] = "Сяо Я"; /* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value -String? name = map[15937]; +// Ввести в хеш-таблицу ключ key и получить значение value +final String? name = map[15937]; /* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы +// Удалить пару (key, value) из хеш-таблицы map.remove(10583); ``` ```rust title="hash_map.rs" use std::collections::HashMap; -/* Инициализация хеш-таблицы */ -let mut map: HashMap = HashMap::new(); +// Инициализация хеш-таблицы +let mut map = HashMap::new(); -/* Операция добавления */ -// Добавить пару ключ-значение (key, value) в хеш-таблицу -map.insert(12836, "Сяо Ха".to_string()); -map.insert(15937, "Сяо Ло".to_string()); -map.insert(16750, "Сяо Суань".to_string()); -map.insert(13276, "Сяо Фа".to_string()); -map.insert(10583, "Сяо Я".to_string()); +// Операция добавления +// Добавить пару (key, value) в хеш-таблицу +map.insert(12836, "Сяо Ха"); +map.insert(15937, "Сяо Ло"); +map.insert(16750, "Сяо Суань"); +map.insert(13276, "Сяо Фа"); +map.insert(10583, "Сяо Я"); -/* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value -let _name: Option<&String> = map.get(&15937); +// Операция поиска +// Передать ключ key в хеш-таблицу и получить значение value +let name = map.get(&15937).copied().unwrap(); -/* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы -let _removed_value: Option = map.remove(&10583); +// Операция удаления +// Удалить пару (key, value) из хеш-таблицы +_ = map.remove(&10583); ``` ```c title="hash_map.c" @@ -220,10 +217,10 @@ let _removed_value: Option = map.remove(&10583); ```kotlin title="hash_map.kt" /* Инициализация хеш-таблицы */ -val map = HashMap() +val map = HashMap() /* Операция добавления */ -// Добавить пару ключ-значение (key, value) в хеш-таблицу +// Добавить пару (key, value) в хеш-таблицу map[12836] = "Сяо Ха" map[15937] = "Сяо Ло" map[16750] = "Сяо Суань" @@ -231,11 +228,11 @@ map[13276] = "Сяо Фа" map[10583] = "Сяо Я" /* Операция поиска */ -// Передать в хеш-таблицу ключ key и получить значение value +// Ввести в хеш-таблицу ключ key и получить значение value val name = map[15937] /* Операция удаления */ -// Удалить пару ключ-значение (key, value) из хеш-таблицы +// Удалить пару (key, value) из хеш-таблицы map.remove(10583) ``` @@ -244,7 +241,7 @@ map.remove(10583) hmap = {} # Операция добавления -# Добавить пару ключ-значение (key, value) в хеш-таблицу +# Добавить пару (key, value) в хеш-таблицу hmap[12836] = "Сяо Ха" hmap[15937] = "Сяо Ло" hmap[16750] = "Сяо Суань" @@ -252,11 +249,11 @@ hmap[13276] = "Сяо Фа" hmap[10583] = "Сяо Я" # Операция поиска -# Передать в хеш-таблицу ключ key и получить значение value +# Передать ключ key в хеш-таблицу и получить значение value name = hmap[15937] # Операция удаления -# Удалить пару ключ-значение (key, value) из хеш-таблицы +# Удалить пару (key, value) из хеш-таблицы hmap.delete(10583) ``` @@ -269,52 +266,59 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 # Обход пар ключ-значение key->value for key, value in hmap.items(): print(key, "->", value) + # Обход только ключей key for key in hmap.keys(): print(key) + # Обход только значений value -for value in hmap.values(): - print(value) +for val in hmap.values(): + print(val) ``` ```cpp title="hash_map.cpp" /* Обход хеш-таблицы */ // Обход пар ключ-значение key->value -for (auto kv: map) { +for (auto kv : map) { cout << kv.first << " -> " << kv.second << endl; } + // Обход key->value с помощью итератора for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; + cout << iter->first << " -> " << iter->second << endl; } ``` ```java title="hash_map.java" /* Обход хеш-таблицы */ // Обход пар ключ-значение key->value -for (Map.Entry kv: map.entrySet()) { +for (Map.Entry kv : map.entrySet()) { System.out.println(kv.getKey() + " -> " + kv.getValue()); } + // Обход только ключей key -for (int key: map.keySet()) { +for (int key : map.keySet()) { System.out.println(key); } + // Обход только значений value -for (String val: map.values()) { +for (String val : map.values()) { System.out.println(val); } ``` ```csharp title="hash_map.cs" /* Обход хеш-таблицы */ -// Обход пар ключ-значение Key->Value +// Обход пар ключ-значение key->value foreach (var kv in map) { Console.WriteLine(kv.Key + " -> " + kv.Value); } + // Обход только ключей key foreach (int key in map.Keys) { Console.WriteLine(key); } + // Обход только значений value foreach (string val in map.Values) { Console.WriteLine(val); @@ -327,10 +331,12 @@ foreach (string val in map.Values) { for key, value := range hmap { fmt.Println(key, "->", value) } + // Обход только ключей key for key := range hmap { fmt.Println(key) } + // Обход только значений value for _, value := range hmap { fmt.Println(value) @@ -339,15 +345,17 @@ for _, value := range hmap { ```swift title="hash_map.swift" /* Обход хеш-таблицы */ -// Обход пар ключ-значение Key->Value +// Обход пар ключ-значение key->value for (key, value) in map { print("\(key) -> \(value)") } -// Обход только ключей Key + +// Обход только ключей key for key in map.keys { print(key) } -// Обход только значений Value + +// Обход только значений value for value in map.values { print(value) } @@ -355,15 +363,17 @@ for value in map.values { ```javascript title="hash_map.js" /* Обход хеш-таблицы */ -console.info('\nОбход пар ключ-значение Key->Value'); +// Обход пар ключ-значение key->value for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\nОбход только ключей Key'); + +// Обход только ключей key for (const k of map.keys()) { console.info(k); } -console.info('\nОбход только значений Value'); + +// Обход только значений value for (const v of map.values()) { console.info(v); } @@ -371,15 +381,17 @@ for (const v of map.values()) { ```typescript title="hash_map.ts" /* Обход хеш-таблицы */ -console.info('\nОбход пар ключ-значение Key->Value'); +// Обход пар ключ-значение key->value for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\nОбход только ключей Key'); + +// Обход только ключей key for (const k of map.keys()) { console.info(k); } -console.info('\nОбход только значений Value'); + +// Обход только значений value for (const v of map.values()) { console.info(v); } @@ -387,35 +399,29 @@ for (const v of map.values()) { ```dart title="hash_map.dart" /* Обход хеш-таблицы */ -// Обход пар ключ-значение Key->Value -map.forEach((key, value) { - print('$key -> $value'); -}); +// Обход пар ключ-значение key->value +map.forEach((key, value) => print("$key -> $value")); -// Обход только ключей Key -map.keys.forEach((key) { - print(key); -}); +// Обход только ключей key +map.keys.forEach((key) => print(key)); -// Обход только значений Value -map.values.forEach((value) { - print(value); -}); +// Обход только значений value +map.values.forEach((value) => print(value)); ``` ```rust title="hash_map.rs" -/* Обход хеш-таблицы */ -// Обход пар ключ-значение Key->Value +// Обход хеш-таблицы +// Обход пар ключ-значение key->value for (key, value) in &map { println!("{key} -> {value}"); } -// Обход только ключей Key +// Обход только ключей key for key in map.keys() { println!("{key}"); } -// Обход только значений Value +// Обход только значений value for value in map.values() { println!("{value}"); } @@ -431,10 +437,12 @@ for value in map.values() { for ((key, value) in map) { println("$key -> $value") } + // Обход только ключей key for (key in map.keys) { println(key) } + // Обход только значений value for (_val in map.values) { println(_val) @@ -454,4 +462,4 @@ hmap.values.each { |val| puts val } ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D0%B4%D0%BE%D0%B1%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%20%D0%BF%D0%B0%D1%80%D1%83%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%9B%D0%BE%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A1%D1%83%D0%B0%D0%BD%D1%8C%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A4%D0%B0%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%D0%A3%D1%82%D0%B5%D0%BD%D0%BE%D0%BA%22%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%B5%D1%80%D0%B5%D0%B1%D1%80%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20%23%20%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%BF%D0%B0%D1%80%D0%B0%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%D0%BE%D1%82%D0%B4%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%BA%D0%BB%D1%8E%D1%87%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%D0%BE%D1%82%D0%B4%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9E%D0%BF%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F%20%D0%B4%D0%BE%D0%B1%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D1%8F%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D0%B2%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%20%D0%BF%D0%B0%D1%80%D1%83%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A5%D0%B0%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%9B%D0%BE%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A1%D1%83%D0%B0%D0%BD%D1%8C%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%D0%A1%D1%8F%D0%BE%20%D0%A4%D0%B0%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%D0%A3%D1%82%D0%B5%D0%BD%D0%BE%D0%BA%22%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%B5%D1%80%D0%B5%D0%B1%D1%80%D0%B0%D1%82%D1%8C%20%D1%85%D0%B5%D1%88-%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%83%0A%20%20%20%20%23%20%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%BF%D0%B0%D1%80%D0%B0%20%D0%BA%D0%BB%D1%8E%D1%87-%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%D0%BE%D1%82%D0%B4%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%BA%D0%BB%D1%8E%D1%87%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%D0%BE%D1%82%D0%B4%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D0%9E%D0%B1%D0%BE%D0%B9%D1%82%D0%B8%D0%B7%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20value%0A%20%20%20%20for%20val%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28val%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_heap/heap.md b/ru/codes/snippets/chapter_heap/heap.md index 37f1ae32e..566960376 100644 --- a/ru/codes/snippets/chapter_heap/heap.md +++ b/ru/codes/snippets/chapter_heap/heap.md @@ -6,26 +6,26 @@ min_heap, flag = [], 1 max_heap, flag = [], -1 # Модуль heapq в Python по умолчанию реализует минимальную кучу -# Если инвертировать знак элемента перед добавлением, то отношение порядка перевернется и так реализуется максимальная куча -# В этом примере flag = 1 соответствует минимальной куче, а flag = -1 - максимальной +# Можно помещать в кучу отрицательные элементы, чтобы инвертировать отношение порядка и таким образом реализовать максимальную кучу +# В этом примере flag = 1 соответствует минимальной куче, а flag = -1 — максимальной куче -# Добавление элементов в кучу +# Добавление элемента в кучу heapq.heappush(max_heap, flag * 1) heapq.heappush(max_heap, flag * 3) heapq.heappush(max_heap, flag * 2) heapq.heappush(max_heap, flag * 5) heapq.heappush(max_heap, flag * 4) -# Получение элемента на вершине кучи -peek: int = flag * max_heap[0] # 5 +# Получение элемента с вершины кучи +peek: int = flag * max_heap[0] # 5 # Извлечение элемента с вершины кучи # Извлеченные элементы образуют последовательность по убыванию -val = flag * heapq.heappop(max_heap) # 5 -val = flag * heapq.heappop(max_heap) # 4 -val = flag * heapq.heappop(max_heap) # 3 -val = flag * heapq.heappop(max_heap) # 2 -val = flag * heapq.heappop(max_heap) # 1 +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 # Получение размера кучи size: int = len(max_heap) @@ -33,26 +33,27 @@ size: int = len(max_heap) # Проверка, пуста ли куча is_empty: bool = not max_heap -# Построение кучи из входного списка +# Создать кучу по входному списку +# Временная сложность равна O(n), а не O(nlogn) min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) ``` ```cpp title="heap.cpp" /* Инициализация кучи */ -// Инициализация минимальной кучи +// Инициализировать минимальную кучу priority_queue, greater> minHeap; -// Инициализация максимальной кучи +// Инициализировать максимальную кучу priority_queue, less> maxHeap; -/* Добавление элементов в кучу */ +/* Добавление элемента в кучу */ maxHeap.push(1); maxHeap.push(3); maxHeap.push(2); maxHeap.push(5); maxHeap.push(4); -/* Получение элемента на вершине кучи */ +/* Получение элемента с вершины кучи */ int peek = maxHeap.top(); // 5 /* Извлечение элемента с вершины кучи */ @@ -69,7 +70,8 @@ int size = maxHeap.size(); /* Проверка, пуста ли куча */ bool isEmpty = maxHeap.empty(); -/* Построение кучи из входного списка */ +/* Построить кучу по входному списку */ +// Временная сложность равна O(n), а не O(nlogn) vector input{1, 3, 2, 5, 4}; minHeap = priority_queue, greater>(input.begin(), input.end()); ``` @@ -78,17 +80,17 @@ minHeap = priority_queue, greater>(input.begin(), input.en /* Инициализация кучи */ // Инициализация минимальной кучи Queue minHeap = new PriorityQueue<>(); -// Инициализация максимальной кучи (достаточно изменить Comparator через lambda) +// Инициализация максимальной кучи (достаточно изменить Comparator с помощью lambda-выражения) Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); -/* Добавление элементов в кучу */ +/* Добавление элемента в кучу */ maxHeap.offer(1); maxHeap.offer(3); maxHeap.offer(2); maxHeap.offer(5); maxHeap.offer(4); -/* Получение элемента на вершине кучи */ +/* Получение элемента с вершины кучи */ int peek = maxHeap.peek(); // 5 /* Извлечение элемента с вершины кучи */ @@ -105,7 +107,8 @@ int size = maxHeap.size(); /* Проверка, пуста ли куча */ boolean isEmpty = maxHeap.isEmpty(); -/* Построение кучи из входного списка */ +/* Построить кучу по входному списку */ +// Временная сложность равна O(n), а не O(nlogn) minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); ``` @@ -113,26 +116,26 @@ minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); /* Инициализация кучи */ // Инициализация минимальной кучи PriorityQueue minHeap = new(); -// Инициализация максимальной кучи (достаточно изменить Comparer через lambda) +// Инициализировать максимальную кучу (достаточно изменить Comparer с помощью lambda-выражения) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); -/* Добавление элементов в кучу */ +/* Добавление элемента в кучу */ maxHeap.Enqueue(1, 1); maxHeap.Enqueue(3, 3); maxHeap.Enqueue(2, 2); maxHeap.Enqueue(5, 5); maxHeap.Enqueue(4, 4); -/* Получение элемента на вершине кучи */ -int peek = maxHeap.Peek();//5 +/* Получение элемента с вершины кучи */ +int peek = maxHeap.Peek(); // 5 /* Извлечение элемента с вершины кучи */ -// Извлеченные элементы образуют последовательность по убыванию -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +// Элементы, извлеченные из кучи, образуют последовательность от большего к меньшему +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 /* Получение размера кучи */ int size = maxHeap.Count; @@ -140,80 +143,81 @@ int size = maxHeap.Count; /* Проверка, пуста ли куча */ bool isEmpty = maxHeap.Count == 0; -/* Построение кучи из входного списка */ +/* Построить кучу по входному списку */ +// Временная сложность равна O(n), а не O(nlogn) minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); ``` ```go title="heap.go" -// В Go можно построить целочисленную максимальную кучу, реализовав heap.Interface -// Для реализации heap.Interface также нужно реализовать sort.Interface +// В Go можно построить максимальную кучу для целых чисел, реализовав heap.Interface +// Для реализации heap.Interface одновременно требуется реализовать sort.Interface type intHeap []any -// Метод Push из heap.Interface, реализует добавление элемента в кучу +// Функция Push интерфейса heap.Interface, реализующая добавление элемента в кучу func (h *intHeap) Push(x any) { - // Push и Pop используют pointer receiver - // Потому что они не только изменяют содержимое среза, но и его длину + // Push и Pop используют pointer receiver в качестве параметра + // Потому что они не только изменяют содержимое среза, но и меняют его длину. *h = append(*h, x.(int)) } -// Метод Pop из heap.Interface, реализует извлечение элемента с вершины кучи +// Функция Pop интерфейса heap.Interface, реализующая извлечение элемента с вершины кучи func (h *intHeap) Pop() any { - // Извлекаемый элемент хранится в конце + // Элемент, который нужно удалить из кучи, хранится в конце last := (*h)[len(*h)-1] *h = (*h)[:len(*h)-1] return last } -// Метод Len из sort.Interface +// Функция Len интерфейса sort.Interface func (h *intHeap) Len() int { return len(*h) } -// Метод Less из sort.Interface +// Функция Less интерфейса sort.Interface func (h *intHeap) Less(i, j int) bool { - // Для минимальной кучи здесь нужно заменить сравнение на < + // При реализации минимальной кучи нужно изменить знак сравнения на «меньше» return (*h)[i].(int) > (*h)[j].(int) } -// Метод Swap из sort.Interface +// Функция Swap интерфейса sort.Interface func (h *intHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } -// Top получает элемент на вершине кучи +// Top: получить элемент на вершине кучи func (h *intHeap) Top() any { return (*h)[0] } -/* Driver Code */ func TestHeap(t *testing.T) { /* Инициализация кучи */ // Инициализация максимальной кучи maxHeap := &intHeap{} heap.Init(maxHeap) - /* Добавление элементов в кучу */ - // Вызываем методы heap.Interface для добавления элементов + /* Добавление элемента в кучу */ + // Вызвать функции heap.Interface для добавления элемента heap.Push(maxHeap, 1) heap.Push(maxHeap, 3) heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) - /* Получение элемента на вершине кучи */ + /* Получение элемента с вершины кучи */ top := maxHeap.Top() - fmt.Printf("Элемент на вершине кучи: %d\n", top) + fmt.Printf("Элемент на вершине кучи = %d\n", top) /* Извлечение элемента с вершины кучи */ - // Вызываем методы heap.Interface для удаления элементов - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 + // Вызвать функции heap.Interface для удаления элемента + fmt.Printf("Извлеченный элемент = %d\n", heap.Pop(maxHeap)) // 5 + fmt.Printf("Извлеченный элемент = %d\n", heap.Pop(maxHeap)) // 4 + fmt.Printf("Извлеченный элемент = %d\n", heap.Pop(maxHeap)) // 3 + fmt.Printf("Извлеченный элемент = %d\n", heap.Pop(maxHeap)) // 2 + fmt.Printf("Извлеченный элемент = %d\n", heap.Pop(maxHeap)) // 1 /* Получение размера кучи */ size := len(*maxHeap) - fmt.Printf("Число элементов в куче: %d\n", size) + fmt.Printf("Количество элементов в куче = %d\n", size) /* Проверка, пуста ли куча */ isEmpty := len(*maxHeap) == 0 @@ -222,19 +226,21 @@ func TestHeap(t *testing.T) { ``` ```swift title="heap.swift" +import HeapModule + /* Инициализация кучи */ -// Тип Heap в Swift поддерживает и max-heap, и min-heap, но требует swift-collections +// Тип Heap в Swift одновременно поддерживает максимальную и минимальную кучу; требуется пакет swift-collections var heap = Heap() -/* Добавление элементов в кучу */ +/* Добавление элемента в кучу */ heap.insert(1) heap.insert(3) heap.insert(2) heap.insert(5) heap.insert(4) -/* Получение элемента на вершине кучи */ -var peek = heap.max()! +/* Получение элемента с вершины кучи */ +var peek = heap.max() /* Извлечение элемента с вершины кучи */ peek = heap.removeMax() // 5 @@ -249,7 +255,8 @@ let size = heap.count /* Проверка, пуста ли куча */ let isEmpty = heap.isEmpty -/* Построение кучи из входного списка */ +/* Построить кучу по входному списку */ +// Временная сложность равна O(n), а не O(nlogn) let heap2 = Heap([1, 3, 2, 5, 4]) ``` @@ -266,32 +273,33 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +use std::{cmp::Reverse, collections::BinaryHeap}; /* Инициализация кучи */ // Инициализация минимальной кучи -let mut min_heap = BinaryHeap::>::new(); -// Инициализация максимальной кучи +// BinaryHeap в Rust является максимальной кучей; для минимальной кучи элементы нужно оборачивать в Reverse +#[allow(unused_assignments)] +let mut min_heap = BinaryHeap::new(); +// Инициализировать максимальную кучу let mut max_heap = BinaryHeap::new(); -/* Добавление элементов в кучу */ +/* Добавление элемента в кучу */ max_heap.push(1); max_heap.push(3); max_heap.push(2); max_heap.push(5); max_heap.push(4); -/* Получение элемента на вершине кучи */ -let peek = max_heap.peek().unwrap(); // 5 +/* Получение элемента с вершины кучи */ +let peek = max_heap.peek().unwrap(); // 5 /* Извлечение элемента с вершины кучи */ // Извлеченные элементы образуют последовательность по убыванию -let peek = max_heap.pop().unwrap(); // 5 -let peek = max_heap.pop().unwrap(); // 4 -let peek = max_heap.pop().unwrap(); // 3 -let peek = max_heap.pop().unwrap(); // 2 -let peek = max_heap.pop().unwrap(); // 1 +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 /* Получение размера кучи */ let size = max_heap.len(); @@ -299,8 +307,9 @@ let size = max_heap.len(); /* Проверка, пуста ли куча */ let is_empty = max_heap.is_empty(); -/* Построение кучи из входного списка */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +/* Построить кучу по входному списку */ +// Временная сложность равна O(n), а не O(nlogn) +min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); ``` ```c title="heap.c" @@ -311,17 +320,17 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse /* Инициализация кучи */ // Инициализация минимальной кучи var minHeap = PriorityQueue() -// Инициализация максимальной кучи (достаточно изменить Comparator через lambda) +// Инициализация максимальной кучи (достаточно изменить Comparator с помощью lambda-выражения) val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } -/* Добавление элементов в кучу */ +/* Добавление элемента в кучу */ maxHeap.offer(1) maxHeap.offer(3) maxHeap.offer(2) maxHeap.offer(5) maxHeap.offer(4) -/* Получение элемента на вершине кучи */ +/* Получение элемента с вершины кучи */ var peek = maxHeap.peek() // 5 /* Извлечение элемента с вершины кучи */ @@ -338,8 +347,9 @@ val size = maxHeap.size /* Проверка, пуста ли куча */ val isEmpty = maxHeap.isEmpty() -/* Построение кучи из входного списка */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +/* Построить кучу по входному списку */ +// Временная сложность равна O(n), а не O(nlogn) +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` ```ruby title="heap.rb" @@ -347,4 +357,4 @@ minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` -https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20min-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20max-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9C%D0%BE%D0%B4%D1%83%D0%BB%D1%8C%20heapq%20%D0%B2%20Python%20%D0%BF%D0%BE%20%D1%83%D0%BC%D0%BE%D0%BB%D1%87%D0%B0%D0%BD%D0%B8%D1%8E%20%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D1%83%D0%B5%D1%82%20min-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20%23%20%D0%95%D1%81%D0%BB%D0%B8%20%D0%BF%D0%B5%D1%80%D0%B5%D0%B4%20%D0%BF%D0%BE%D0%BC%D0%B5%D1%89%D0%B5%D0%BD%D0%B8%D0%B5%D0%BC%20%D0%B2%20%D0%BA%D1%83%D1%87%D1%83%20%D0%B1%D1%80%D0%B0%D1%82%D1%8C%20%D0%BE%D1%82%D1%80%D0%B8%D1%86%D0%B0%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%2C%20%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%20%D0%BE%D0%B1%D1%80%D0%B0%D1%82%D0%B8%D1%82%D1%8C%20%D0%BE%D1%82%D0%BD%D0%BE%D1%88%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BF%D0%BE%D1%80%D1%8F%D0%B4%D0%BA%D0%B0%20%D0%B8%20%D1%82%D0%B5%D0%BC%20%D1%81%D0%B0%D0%BC%D1%8B%D0%BC%20%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20max-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20%23%20%D0%92%20%D1%8D%D1%82%D0%BE%D0%BC%20%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D0%B5%20flag%20%3D%201%20%D1%81%D0%BE%D0%BE%D1%82%D0%B2%D0%B5%D1%82%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82%20min-%D0%BA%D1%83%D1%87%D0%B5%2C%20%D0%B0%20flag%20%3D%20-1%20%D1%81%D0%BE%D0%BE%D1%82%D0%B2%D0%B5%D1%82%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82%20max-%D0%BA%D1%83%D1%87%D0%B5%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5%20%D0%B8%D0%B7%20%D0%BA%D1%83%D1%87%D0%B8%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%8B%20%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D1%83%D1%8E%D1%82%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C%20%D0%BE%D1%82%20%D0%B1%D0%BE%D0%BB%D1%8C%D1%88%D0%B5%D0%B3%D0%BE%20%D0%BA%20%D0%BC%D0%B5%D0%BD%D1%8C%D1%88%D0%B5%D0%BC%D1%83%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D1%80%D0%B0%D0%B7%D0%BC%D0%B5%D1%80%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%BA%D1%83%D1%87%D0%B0%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%92%D1%85%D0%BE%D0%B4%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D0%B8%D0%BF%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20min-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20max-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9C%D0%BE%D0%B4%D1%83%D0%BB%D1%8C%20heapq%20%D0%B2%20Python%20%D0%BF%D0%BE%20%D1%83%D0%BC%D0%BE%D0%BB%D1%87%D0%B0%D0%BD%D0%B8%D1%8E%20%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D1%83%D0%B5%D1%82%20min-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20%23%20%D0%95%D1%81%D0%BB%D0%B8%20%D0%BF%D0%B5%D1%80%D0%B5%D0%B4%20%D0%BF%D0%BE%D0%BC%D0%B5%D1%89%D0%B5%D0%BD%D0%B8%D0%B5%D0%BC%20%D0%B2%20%D0%BA%D1%83%D1%87%D1%83%20%D0%B1%D1%80%D0%B0%D1%82%D1%8C%20%D0%BE%D1%82%D1%80%D0%B8%D1%86%D0%B0%D0%BD%D0%B8%D0%B5%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D0%B0%2C%20%D0%BC%D0%BE%D0%B6%D0%BD%D0%BE%20%D0%BE%D0%B1%D1%80%D0%B0%D1%82%D0%B8%D1%82%D1%8C%20%D0%BE%D1%82%D0%BD%D0%BE%D1%88%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BF%D0%BE%D1%80%D1%8F%D0%B4%D0%BA%D0%B0%20%D0%B8%20%D1%82%D0%B5%D0%BC%20%D1%81%D0%B0%D0%BC%D1%8B%D0%BC%20%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20max-%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20%23%20%D0%92%20%D1%8D%D1%82%D0%BE%D0%BC%20%D0%BF%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D0%B5%20flag%20%3D%201%20%D1%81%D0%BE%D0%BE%D1%82%D0%B2%D0%B5%D1%82%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82%20min-%D0%BA%D1%83%D1%87%D0%B5%2C%20%D0%B0%20flag%20%3D%20-1%20%D1%81%D0%BE%D0%BE%D1%82%D0%B2%D0%B5%D1%82%D1%81%D1%82%D0%B2%D1%83%D0%B5%D1%82%20max-%D0%BA%D1%83%D1%87%D0%B5%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%94%D0%BE%D0%B1%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B2%20%D0%BA%D1%83%D1%87%D1%83%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D1%8C%20%D0%B2%D0%B5%D1%80%D1%85%D0%BD%D0%B8%D0%B9%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%20%D0%B8%D0%B7%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20%23%20%D0%98%D0%B7%D0%B2%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%BD%D1%8B%D0%B5%20%D0%B8%D0%B7%20%D0%BA%D1%83%D1%87%D0%B8%20%D1%8D%D0%BB%D0%B5%D0%BC%D0%B5%D0%BD%D1%82%D1%8B%20%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D1%83%D1%8E%D1%82%20%D0%BF%D0%BE%D1%81%D0%BB%D0%B5%D0%B4%D0%BE%D0%B2%D0%B0%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D0%BE%D1%81%D1%82%D1%8C%20%D0%BE%D1%82%20%D0%B1%D0%BE%D0%BB%D1%8C%D1%88%D0%B5%D0%B3%D0%BE%20%D0%BA%20%D0%BC%D0%B5%D0%BD%D1%8C%D1%88%D0%B5%D0%BC%D1%83%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D0%BE%D0%BB%D1%83%D1%87%D0%B8%D1%82%D1%8C%20%D1%80%D0%B0%D0%B7%D0%BC%D0%B5%D1%80%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%B8%D1%82%D1%8C%2C%20%D0%BF%D1%83%D1%81%D1%82%D0%B0%20%D0%BB%D0%B8%20%D0%BA%D1%83%D1%87%D0%B0%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%D0%92%D1%85%D0%BE%D0%B4%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA%D0%B8%D0%BF%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%BA%D1%83%D1%87%D0%B8%0A%20%20%20%20%23%20%D0%92%D1%80%D0%B5%D0%BC%D0%B5%D0%BD%D0%BD%D0%B0%D1%8F%20%D1%81%D0%BB%D0%BE%D0%B6%D0%BD%D0%BE%D1%81%D1%82%D1%8C%20%D1%80%D0%B0%D0%B2%D0%BD%D0%B0%20O%28n%29%2C%20%D0%B0%20%D0%BD%D0%B5%20O%28nlogn%29%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/snippets/chapter_stack_and_queue/deque.md b/ru/codes/snippets/chapter_stack_and_queue/deque.md index 6fa64b46b..b37092307 100644 --- a/ru/codes/snippets/chapter_stack_and_queue/deque.md +++ b/ru/codes/snippets/chapter_stack_and_queue/deque.md @@ -5,25 +5,25 @@ from collections import deque # Инициализация двусторонней очереди deq: deque[int] = deque() -# Поместить элементы в очередь -deq.append(2) # Добавить в хвост +# Добавление элемента в очередь +deq.append(2) # Добавить в хвост очереди deq.append(5) deq.append(4) -deq.appendleft(3) # Добавить в голову +deq.appendleft(3) # Добавить в голову очереди deq.appendleft(1) -# Просмотреть элементы -front: int = deq[0] # Элемент в голове -rear: int = deq[-1] # Элемент в хвосте +# Доступ к элементу +front: int = deq[0] # Элемент в голове очереди +rear: int = deq[-1] # Элемент в хвосте очереди -# Извлечь элементы из очереди -pop_front: int = deq.popleft() # Извлечь элемент из головы -pop_rear: int = deq.pop() # Извлечь элемент из хвоста +# Извлечение элемента из очереди +pop_front: int = deq.popleft() # Извлечь элемент из головы очереди +pop_rear: int = deq.pop() # Извлечь элемент из хвоста очереди -# Получить длину двусторонней очереди +# Получение длины двусторонней очереди size: int = len(deq) -# Проверить, пуста ли двусторонняя очередь +# Проверка, пуста ли двусторонняя очередь is_empty: bool = len(deq) == 0 ``` @@ -31,25 +31,25 @@ is_empty: bool = len(deq) == 0 /* Инициализация двусторонней очереди */ deque deque; -/* Поместить элементы в очередь */ -deque.push_back(2); // Добавить в хвост +/* Добавление элемента в очередь */ +deque.push_back(2); // Добавить в хвост deque.push_back(5); deque.push_back(4); -deque.push_front(3); // Добавить в голову +deque.push_front(3); // Добавить в голову deque.push_front(1); -/* Просмотреть элементы */ +/* Доступ к элементу */ int front = deque.front(); // Элемент в голове -int back = deque.back(); // Элемент в хвосте +int back = deque.back(); // Элемент в хвосте -/* Извлечь элементы из очереди */ -deque.pop_front(); // Извлечь элемент из головы -deque.pop_back(); // Извлечь элемент из хвоста +/* Извлечение элемента из очереди */ +deque.pop_front(); // Извлечь элемент из головы +deque.pop_back(); // Извлечь элемент из хвоста -/* Получить длину двусторонней очереди */ +/* Получение длины двусторонней очереди */ int size = deque.size(); -/* Проверить, пуста ли двусторонняя очередь */ +/* Проверка, пуста ли двусторонняя очередь */ bool empty = deque.empty(); ``` @@ -57,222 +57,218 @@ bool empty = deque.empty(); /* Инициализация двусторонней очереди */ Deque deque = new LinkedList<>(); -/* Поместить элементы в очередь */ -deque.offerLast(2); // Добавить в хвост +/* Добавление элемента в очередь */ +deque.offerLast(2); // Добавить в хвост deque.offerLast(5); deque.offerLast(4); -deque.offerFirst(3); // Добавить в голову +deque.offerFirst(3); // Добавить в голову deque.offerFirst(1); -/* Просмотреть элементы */ -int peekFirst = deque.peekFirst(); // Элемент в голове -int peekLast = deque.peekLast(); // Элемент в хвосте +/* Доступ к элементу */ +int peekFirst = deque.peekFirst(); // Элемент в голове +int peekLast = deque.peekLast(); // Элемент в хвосте -/* Извлечь элементы из очереди */ -int popFirst = deque.pollFirst(); // Извлечь элемент из головы -int popLast = deque.pollLast(); // Извлечь элемент из хвоста +/* Извлечение элемента из очереди */ +int popFirst = deque.pollFirst(); // Извлечь элемент из головы +int popLast = deque.pollLast(); // Извлечь элемент из хвоста -/* Получить длину двусторонней очереди */ +/* Получение длины двусторонней очереди */ int size = deque.size(); -/* Проверить, пуста ли двусторонняя очередь */ +/* Проверка, пуста ли двусторонняя очередь */ boolean isEmpty = deque.isEmpty(); ``` ```csharp title="deque.cs" /* Инициализация двусторонней очереди */ -// В C# двустороннюю очередь обычно моделируют через связный список LinkedList +// В C# связный список LinkedList рассматривается как двусторонняя очередь LinkedList deque = new(); -/* Поместить элементы в очередь */ -deque.AddLast(2); // Добавить в хвост +/* Добавление элемента в очередь */ +deque.AddLast(2); // Добавить в хвост очереди deque.AddLast(5); deque.AddLast(4); -deque.AddFirst(3); // Добавить в голову +deque.AddFirst(3); // Добавить в голову очереди deque.AddFirst(1); -/* Просмотреть элементы */ -int peekFirst = deque.First.Value; // Элемент в голове -int peekLast = deque.Last.Value; // Элемент в хвосте +/* Доступ к элементу */ +int? peekFirst = deque.First?.Value; // Элемент в голове очереди +int? peekLast = deque.Last?.Value; // Элемент в хвосте очереди -/* Извлечь элементы из очереди */ -deque.RemoveFirst(); // Извлечь элемент из головы -deque.RemoveLast(); // Извлечь элемент из хвоста +/* Извлечение элемента из очереди */ +deque.RemoveFirst(); // Извлечь элемент из головы очереди +deque.RemoveLast(); // Извлечь элемент из хвоста очереди -/* Получить длину двусторонней очереди */ +/* Получение длины двусторонней очереди */ int size = deque.Count; -/* Проверить, пуста ли двусторонняя очередь */ +/* Проверка, пуста ли двусторонняя очередь */ bool isEmpty = deque.Count == 0; ``` ```go title="deque_test.go" /* Инициализация двусторонней очереди */ -// В Go list обычно используется как двусторонняя очередь +// В Go list используется как двусторонняя очередь deque := list.New() -/* Поместить элементы в очередь */ -deque.PushBack(2) // Добавить в хвост +/* Добавление элемента в очередь */ +deque.PushBack(2) // Добавить в хвост deque.PushBack(5) deque.PushBack(4) -deque.PushFront(3) // Добавить в голову +deque.PushFront(3) // Добавить в голову deque.PushFront(1) -/* Просмотреть элементы */ +/* Доступ к элементу */ front := deque.Front() // Элемент в голове -rear := deque.Back() // Элемент в хвосте +rear := deque.Back() // Элемент в хвосте -/* Извлечь элементы из очереди */ -deque.Remove(front) // Извлечь элемент из головы -deque.Remove(rear) // Извлечь элемент из хвоста +/* Извлечение элемента из очереди */ +deque.Remove(front) // Извлечь элемент из головы +deque.Remove(rear) // Извлечь элемент из хвоста -/* Получить длину двусторонней очереди */ +/* Получение длины двусторонней очереди */ size := deque.Len() -/* Проверить, пуста ли двусторонняя очередь */ +/* Проверка, пуста ли двусторонняя очередь */ isEmpty := deque.Len() == 0 ``` ```swift title="deque.swift" /* Инициализация двусторонней очереди */ -// В Swift нет встроенного класса двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь +// В Swift нет встроенного класса двусторонней очереди, поэтому Array можно использовать как двустороннюю очередь var deque: [Int] = [] -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ deque.append(2) // Добавить в хвост deque.append(5) deque.append(4) deque.insert(3, at: 0) // Добавить в голову deque.insert(1, at: 0) -/* Просмотреть элементы */ +/* Доступ к элементу */ let peekFirst = deque.first! // Элемент в голове let peekLast = deque.last! // Элемент в хвосте -/* Извлечь элементы из очереди */ -// При моделировании через Array сложность popFirst равна O(n) +/* Извлечение элемента из очереди */ +// При использовании Array для имитации removeFirst имеет сложность O(n) let popFirst = deque.removeFirst() // Извлечь элемент из головы let popLast = deque.removeLast() // Извлечь элемент из хвоста -/* Получить длину двусторонней очереди */ +/* Получение длины двусторонней очереди */ let size = deque.count -/* Проверить, пуста ли двусторонняя очередь */ +/* Проверка, пуста ли двусторонняя очередь */ let isEmpty = deque.isEmpty ``` ```javascript title="deque.js" /* Инициализация двусторонней очереди */ -// В JavaScript нет встроенной двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь +// В JavaScript нет встроенной двусторонней очереди, поэтому Array можно использовать как двустороннюю очередь const deque = []; -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ deque.push(2); deque.push(5); deque.push(4); -// Обратите внимание: поскольку это массив, метод unshift() имеет сложность O(n) +// Обратите внимание: поскольку используется массив, временная сложность метода unshift() равна O(n) deque.unshift(3); deque.unshift(1); -/* Просмотреть элементы */ +/* Доступ к элементу */ const peekFirst = deque[0]; const peekLast = deque[deque.length - 1]; -/* Извлечь элементы из очереди */ -// Обратите внимание: поскольку это массив, метод shift() имеет сложность O(n) +/* Извлечение элемента из очереди */ +// Обратите внимание: поскольку используется массив, временная сложность метода shift() равна O(n) const popFront = deque.shift(); const popBack = deque.pop(); -/* Получить длину двусторонней очереди */ +/* Получение длины двусторонней очереди */ const size = deque.length; -/* Проверить, пуста ли двусторонняя очередь */ +/* Проверка, пуста ли двусторонняя очередь */ const isEmpty = size === 0; ``` ```typescript title="deque.ts" /* Инициализация двусторонней очереди */ -// В TypeScript нет встроенной двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь +// В TypeScript нет встроенной двусторонней очереди, поэтому Array можно использовать как двустороннюю очередь const deque: number[] = []; -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ deque.push(2); deque.push(5); deque.push(4); -// Обратите внимание: поскольку это массив, метод unshift() имеет сложность O(n) +// Обратите внимание: поскольку используется массив, временная сложность метода unshift() равна O(n) deque.unshift(3); deque.unshift(1); -/* Просмотреть элементы */ +/* Доступ к элементу */ const peekFirst: number = deque[0]; const peekLast: number = deque[deque.length - 1]; -/* Извлечь элементы из очереди */ -// Обратите внимание: поскольку это массив, метод shift() имеет сложность O(n) +/* Извлечение элемента из очереди */ +// Обратите внимание: поскольку используется массив, временная сложность метода shift() равна O(n) const popFront: number = deque.shift() as number; const popBack: number = deque.pop() as number; -/* Получить длину двусторонней очереди */ +/* Получение длины двусторонней очереди */ const size: number = deque.length; -/* Проверить, пуста ли двусторонняя очередь */ +/* Проверка, пуста ли двусторонняя очередь */ const isEmpty: boolean = size === 0; ``` ```dart title="deque.dart" /* Инициализация двусторонней очереди */ // В Dart Queue определена как двусторонняя очередь -Queue deque = Queue(); +final Queue deque = Queue(); -/* Поместить элементы в очередь */ -deque.addLast(2); // Добавить в хвост +/* Добавление элемента в очередь */ +deque.addLast(2); // Добавить в хвост deque.addLast(5); deque.addLast(4); deque.addFirst(3); // Добавить в голову deque.addFirst(1); -/* Просмотреть элементы */ -int peekFirst = deque.first; // Элемент в голове -int peekLast = deque.last; // Элемент в хвосте +/* Доступ к элементу */ +final int peekFirst = deque.first; // Элемент в голове +final int peekLast = deque.last; // Элемент в хвосте -/* Извлечь элементы из очереди */ -int popFirst = deque.removeFirst(); // Извлечь элемент из головы -int popLast = deque.removeLast(); // Извлечь элемент из хвоста +/* Извлечение элемента из очереди */ +final int popFirst = deque.removeFirst(); // Извлечь элемент из головы +final int popLast = deque.removeLast(); // Извлечь элемент из хвоста -/* Получить длину двусторонней очереди */ -int size = deque.length; +/* Получение длины двусторонней очереди */ +final int size = deque.length; -/* Проверить, пуста ли двусторонняя очередь */ -bool isEmpty = deque.isEmpty; +/* Проверка, пуста ли двусторонняя очередь */ +final bool isEmpty = deque.isEmpty; ``` ```rust title="deque.rs" -/* Инициализация двусторонней очереди */ -let mut deque: VecDeque = VecDeque::new(); +// Инициализация двусторонней очереди +let mut deque: VecDeque = VecDeque::new(); -/* Поместить элементы в очередь */ -deque.push_back(2); // Добавить в хвост +/* Добавление элемента в очередь */ +deque.push_back(2); // Добавить в хвост deque.push_back(5); deque.push_back(4); deque.push_front(3); // Добавить в голову deque.push_front(1); -/* Просмотреть элементы */ -if let Some(front) = deque.front() { // Элемент в голове -} -if let Some(rear) = deque.back() { // Элемент в хвосте -} +// Доступ к элементу +let peek_first = deque.front().unwrap(); // Элемент в голове +let peek_last = deque.back().unwrap(); // Элемент в хвосте -/* Извлечь элементы из очереди */ -if let Some(pop_front) = deque.pop_front() { // Извлечь элемент из головы -} -if let Some(pop_rear) = deque.pop_back() { // Извлечь элемент из хвоста -} +// Извлечение элемента из очереди +let pop_first = deque.pop_front().unwrap(); // Извлечь элемент из головы +let pop_last = deque.pop_back().unwrap(); // Извлечь элемент из хвоста -/* Получить длину двусторонней очереди */ +// Получение длины двусторонней очереди let size = deque.len(); -/* Проверить, пуста ли двусторонняя очередь */ +// Проверка, пуста ли двусторонняя очередь let is_empty = deque.is_empty(); ``` @@ -284,54 +280,54 @@ let is_empty = deque.is_empty(); /* Инициализация двусторонней очереди */ val deque = LinkedList() -/* Поместить элементы в очередь */ -deque.offerLast(2) // Добавить в хвост +/* Добавление элемента в очередь */ +deque.offerLast(2) // Добавить в хвост deque.offerLast(5) deque.offerLast(4) deque.offerFirst(3) // Добавить в голову deque.offerFirst(1) -/* Просмотреть элементы */ +/* Доступ к элементу */ val peekFirst = deque.peekFirst() // Элемент в голове -val peekLast = deque.peekLast() // Элемент в хвосте +val peekLast = deque.peekLast() // Элемент в хвосте -/* Извлечь элементы из очереди */ +/* Извлечение элемента из очереди */ val popFirst = deque.pollFirst() // Извлечь элемент из головы -val popLast = deque.pollLast() // Извлечь элемент из хвоста +val popLast = deque.pollLast() // Извлечь элемент из хвоста -/* Получить длину двусторонней очереди */ +/* Получение длины двусторонней очереди */ val size = deque.size -/* Проверить, пуста ли двусторонняя очередь */ +/* Проверка, пуста ли двусторонняя очередь */ val isEmpty = deque.isEmpty() ``` ```ruby title="deque.rb" -# Инициализация двусторонней очереди -# В Ruby нет встроенной двусторонней очереди, поэтому можно использовать Array как двустороннюю очередь +# Инициализировать двустороннюю очередь +# В Ruby нет встроенной двусторонней очереди, поэтому Array можно использовать как двустороннюю очередь deque = [] -# Поместить элементы в очередь +# Элемент помещается в очередь deque << 2 deque << 5 deque << 4 -# Обратите внимание: поскольку это массив, метод Array#unshift имеет сложность O(n) +# Обратите внимание: поскольку используется массив, временная сложность метода Array#unshift равна O(n) deque.unshift(3) deque.unshift(1) -# Просмотреть элементы +# Доступ к элементу peek_first = deque.first peek_last = deque.last -# Извлечь элементы из очереди -# Обратите внимание: поскольку это массив, метод Array#shift имеет сложность O(n) +# Элемент извлекается из очереди +# Обратите внимание: поскольку используется массив, временная сложность метода Array#shift равна O(n) pop_front = deque.shift pop_back = deque.pop -# Получить длину двусторонней очереди +# Получение длины двусторонней очереди size = deque.length -# Проверить, пуста ли двусторонняя очередь +# Проверка, пуста ли двусторонняя очередь is_empty = size.zero? ``` diff --git a/ru/codes/snippets/chapter_stack_and_queue/queue.md b/ru/codes/snippets/chapter_stack_and_queue/queue.md index 1a0ccc6be..a674d232f 100644 --- a/ru/codes/snippets/chapter_stack_and_queue/queue.md +++ b/ru/codes/snippets/chapter_stack_and_queue/queue.md @@ -2,28 +2,28 @@ ```python title="queue.py" from collections import deque -# Инициализация очереди -# В Python обычно используют двустороннюю очередь deque как обычную очередь -# Хотя queue.Queue() является "чистой" очередью, она не слишком удобна, поэтому ее не рекомендуют +# Инициализировать очередь +# В Python мы обычно рассматриваем двустороннюю очередь deque как очередь +# Хотя queue.Queue() — это «настоящий» класс очереди, им не очень удобно пользоваться, поэтому ее не рекомендуют que: deque[int] = deque() -# Поместить элементы в очередь +# Добавление элемента в очередь que.append(1) que.append(3) que.append(2) que.append(5) que.append(4) -# Просмотреть элемент в голове очереди +# Доступ к элементу в начале очереди front: int = que[0] -# Извлечь элемент из очереди +# Извлечение элемента из очереди pop: int = que.popleft() -# Получить длину очереди +# Получение длины очереди size: int = len(que) -# Проверить, пуста ли очередь +# Проверка, пуста ли очередь is_empty: bool = len(que) == 0 ``` @@ -31,23 +31,23 @@ is_empty: bool = len(que) == 0 /* Инициализация очереди */ queue queue; -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ queue.push(1); queue.push(3); queue.push(2); queue.push(5); queue.push(4); -/* Просмотреть элемент в голове очереди */ +/* Доступ к элементу в начале очереди */ int front = queue.front(); -/* Извлечь элемент из очереди */ +/* Извлечение элемента из очереди */ queue.pop(); -/* Получить длину очереди */ +/* Получение длины очереди */ int size = queue.size(); -/* Проверить, пуста ли очередь */ +/* Проверка, пуста ли очередь */ bool empty = queue.empty(); ``` @@ -55,23 +55,23 @@ bool empty = queue.empty(); /* Инициализация очереди */ Queue queue = new LinkedList<>(); -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ queue.offer(1); queue.offer(3); queue.offer(2); queue.offer(5); queue.offer(4); -/* Просмотреть элемент в голове очереди */ +/* Доступ к элементу в начале очереди */ int peek = queue.peek(); -/* Извлечь элемент из очереди */ +/* Извлечение элемента из очереди */ int pop = queue.poll(); -/* Получить длину очереди */ +/* Получение длины очереди */ int size = queue.size(); -/* Проверить, пуста ли очередь */ +/* Проверка, пуста ли очередь */ boolean isEmpty = queue.isEmpty(); ``` @@ -79,180 +79,178 @@ boolean isEmpty = queue.isEmpty(); /* Инициализация очереди */ Queue queue = new(); -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ queue.Enqueue(1); queue.Enqueue(3); queue.Enqueue(2); queue.Enqueue(5); queue.Enqueue(4); -/* Просмотреть элемент в голове очереди */ +/* Доступ к элементу в начале очереди */ int peek = queue.Peek(); -/* Извлечь элемент из очереди */ +/* Извлечение элемента из очереди */ int pop = queue.Dequeue(); -/* Получить длину очереди */ +/* Получение длины очереди */ int size = queue.Count; -/* Проверить, пуста ли очередь */ +/* Проверка, пуста ли очередь */ bool isEmpty = queue.Count == 0; ``` ```go title="queue_test.go" /* Инициализация очереди */ -// В Go очередь обычно реализуют через list +// В Go list используется как очередь queue := list.New() -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ queue.PushBack(1) queue.PushBack(3) queue.PushBack(2) queue.PushBack(5) queue.PushBack(4) -/* Просмотреть элемент в голове очереди */ +/* Доступ к элементу в начале очереди */ peek := queue.Front() -/* Извлечь элемент из очереди */ +/* Извлечение элемента из очереди */ pop := queue.Front() queue.Remove(pop) -/* Получить длину очереди */ +/* Получение длины очереди */ size := queue.Len() -/* Проверить, пуста ли очередь */ +/* Проверка, пуста ли очередь */ isEmpty := queue.Len() == 0 ``` ```swift title="queue.swift" /* Инициализация очереди */ -// В Swift нет встроенного класса очереди, поэтому можно использовать Array как очередь +// В Swift нет встроенного класса очереди, поэтому Array можно использовать как очередь var queue: [Int] = [] -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ queue.append(1) queue.append(3) queue.append(2) queue.append(5) queue.append(4) -/* Просмотреть элемент в голове очереди */ +/* Доступ к элементу в начале очереди */ let peek = queue.first! -/* Извлечь элемент из очереди */ -// Поскольку в основе лежит массив, removeFirst имеет сложность O(n) +/* Извлечение элемента из очереди */ +// При использовании Array для имитации removeFirst имеет сложность O(n) let pop = queue.removeFirst() -/* Получить длину очереди */ +/* Получение длины очереди */ let size = queue.count -/* Проверить, пуста ли очередь */ +/* Проверка, пуста ли очередь */ let isEmpty = queue.isEmpty ``` ```javascript title="queue.js" /* Инициализация очереди */ -// В JavaScript нет встроенной очереди, поэтому можно использовать Array как очередь +// В JavaScript нет встроенной очереди, поэтому Array можно использовать как очередь const queue = []; -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ queue.push(1); queue.push(3); queue.push(2); queue.push(5); queue.push(4); -/* Просмотреть элемент в голове очереди */ +/* Доступ к элементу в начале очереди */ const peek = queue[0]; -/* Извлечь элемент из очереди */ -// В основе лежит массив, поэтому shift() имеет сложность O(n) +/* Извлечение элемента из очереди */ +// В основе лежит массив, поэтому временная сложность метода shift() равна O(n) const pop = queue.shift(); -/* Получить длину очереди */ +/* Получение длины очереди */ const size = queue.length; -/* Проверить, пуста ли очередь */ -const empty = queue.length === 0; +/* Проверка, пуста ли очередь */ +const isEmpty = queue.length === 0; ``` ```typescript title="queue.ts" /* Инициализация очереди */ -// В TypeScript нет встроенной очереди, поэтому можно использовать Array как очередь +// В TypeScript нет встроенной очереди, поэтому Array можно использовать как очередь const queue: number[] = []; -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ queue.push(1); queue.push(3); queue.push(2); queue.push(5); queue.push(4); -/* Просмотреть элемент в голове очереди */ +/* Доступ к элементу в начале очереди */ const peek = queue[0]; -/* Извлечь элемент из очереди */ -// В основе лежит массив, поэтому shift() имеет сложность O(n) +/* Извлечение элемента из очереди */ +// В основе лежит массив, поэтому временная сложность метода shift() равна O(n) const pop = queue.shift(); -/* Получить длину очереди */ +/* Получение длины очереди */ const size = queue.length; -/* Проверить, пуста ли очередь */ -const empty = queue.length === 0; +/* Проверка, пуста ли очередь */ +const isEmpty = queue.length === 0; ``` ```dart title="queue.dart" /* Инициализация очереди */ -// В Dart класс Queue является двусторонней очередью и может использоваться как обычная очередь -Queue queue = Queue(); +// В Dart двусторонняя очередь Queue обычно рассматривается как обычная очередь +final Queue queue = Queue(); -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ queue.add(1); queue.add(3); queue.add(2); queue.add(5); queue.add(4); -/* Просмотреть элемент в голове очереди */ -int peek = queue.first; +/* Доступ к элементу в начале очереди */ +final int peek = queue.first; -/* Извлечь элемент из очереди */ -int pop = queue.removeFirst(); +/* Извлечение элемента из очереди */ +final int pop = queue.removeFirst(); /* Получить длину очереди */ -int size = queue.length; +final int size = queue.length; -/* Проверить, пуста ли очередь */ -bool isEmpty = queue.isEmpty; +/* Проверка, пуста ли очередь */ +final bool isEmpty = queue.isEmpty; ``` ```rust title="queue.rs" -/* Инициализация двусторонней очереди */ -// В Rust двусторонняя очередь может использоваться как обычная очередь -let mut deque: VecDeque = VecDeque::new(); +// Инициализация очереди +// В Rust двусторонняя очередь VecDeque обычно используется как очередь +let mut queue: VecDeque = VecDeque::new(); -/* Поместить элементы в очередь */ -deque.push_back(1); -deque.push_back(3); -deque.push_back(2); -deque.push_back(5); -deque.push_back(4); +// Добавление элемента в очередь +queue.push_back(1); +queue.push_back(3); +queue.push_back(2); +queue.push_back(5); +queue.push_back(4); -/* Просмотреть элемент в голове очереди */ -if let Some(front) = deque.front() { -} +// Доступ к элементу в начале очереди +let peek = queue.front().unwrap(); -/* Извлечь элемент из очереди */ -if let Some(pop) = deque.pop_front() { -} +// Извлечение элемента из очереди +let pop = queue.pop_front().unwrap(); -/* Получить длину очереди */ -let size = deque.len(); +// Получение длины очереди +let size = queue.len(); -/* Проверить, пуста ли очередь */ -let is_empty = deque.is_empty(); +// Проверка, пуста ли очередь +let is_empty = queue.is_empty(); ``` ```c title="queue.c" @@ -263,49 +261,49 @@ let is_empty = deque.is_empty(); /* Инициализация очереди */ val queue = LinkedList() -/* Поместить элементы в очередь */ +/* Добавление элемента в очередь */ queue.offer(1) queue.offer(3) queue.offer(2) queue.offer(5) queue.offer(4) -/* Просмотреть элемент в голове очереди */ +/* Доступ к элементу в начале очереди */ val peek = queue.peek() -/* Извлечь элемент из очереди */ +/* Извлечение элемента из очереди */ val pop = queue.poll() -/* Получить длину очереди */ +/* Получение длины очереди */ val size = queue.size -/* Проверить, пуста ли очередь */ +/* Проверка, пуста ли очередь */ val isEmpty = queue.isEmpty() ``` ```ruby title="queue.rb" -# Инициализация очереди -# Встроенная очередь в Ruby (Thread::Queue) не имеет методов peek и traverse, поэтому можно использовать Array как очередь +# Инициализировать очередь +# Во встроенной очереди Ruby (Thread::Queue) нет методов peek и обхода, поэтому Array можно использовать как очередь queue = [] -# Поместить элементы в очередь +# Добавление элемента в очередь queue.push(1) queue.push(3) queue.push(2) queue.push(5) queue.push(4) -# Просмотреть элемент очереди +# Обратиться к элементу очереди peek = queue.first -# Извлечь элемент из очереди -# Обратите внимание: поскольку это массив, метод Array#shift имеет сложность O(n) +# Элемент извлекается из очереди +# Обратите внимание: поскольку используется массив, временная сложность метода Array#shift равна O(n) pop = queue.shift -# Получить длину очереди +# Получение длины очереди size = queue.length -# Проверить, пуста ли очередь +# Проверка, пуста ли очередь is_empty = queue.empty? ``` diff --git a/ru/codes/snippets/chapter_stack_and_queue/stack.md b/ru/codes/snippets/chapter_stack_and_queue/stack.md index 84313a9c7..dc1fec5b5 100644 --- a/ru/codes/snippets/chapter_stack_and_queue/stack.md +++ b/ru/codes/snippets/chapter_stack_and_queue/stack.md @@ -1,26 +1,26 @@ ```python title="stack.py" -# Инициализация стека -# В Python нет встроенного класса стека, поэтому можно использовать list как стек +# Инициализировать стек +# В Python нет встроенного класса стека, поэтому list можно использовать как стек stack: list[int] = [] -# Поместить элементы в стек +# Помещение элемента в стек stack.append(1) stack.append(3) stack.append(2) stack.append(5) stack.append(4) -# Просмотреть верхний элемент +# Доступ к верхнему элементу стека peek: int = stack[-1] -# Извлечь элемент +# Извлечение элемента из стека pop: int = stack.pop() -# Получить длину стека +# Получение длины стека size: int = len(stack) -# Проверить, пуст ли стек +# Проверка на пустоту is_empty: bool = len(stack) == 0 ``` @@ -28,23 +28,23 @@ is_empty: bool = len(stack) == 0 /* Инициализация стека */ stack stack; -/* Поместить элементы в стек */ +/* Помещение элемента в стек */ stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* Просмотреть верхний элемент */ +/* Доступ к верхнему элементу стека */ int top = stack.top(); -/* Извлечь элемент */ +/* Извлечение элемента из стека */ stack.pop(); // Без возвращаемого значения -/* Получить длину стека */ +/* Получение длины стека */ int size = stack.size(); -/* Проверить, пуст ли стек */ +/* Проверка на пустоту */ bool empty = stack.empty(); ``` @@ -52,23 +52,23 @@ bool empty = stack.empty(); /* Инициализация стека */ Stack stack = new Stack<>(); -/* Поместить элементы в стек */ +/* Помещение элемента в стек */ stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* Просмотреть верхний элемент */ +/* Доступ к верхнему элементу стека */ int peek = stack.peek(); -/* Извлечь элемент */ +/* Извлечение элемента из стека */ int pop = stack.pop(); -/* Получить длину стека */ +/* Получение длины стека */ int size = stack.size(); -/* Проверить, пуст ли стек */ +/* Проверка на пустоту */ boolean isEmpty = stack.isEmpty(); ``` @@ -76,23 +76,23 @@ boolean isEmpty = stack.isEmpty(); /* Инициализация стека */ Stack stack = new(); -/* Поместить элементы в стек */ +/* Помещение элемента в стек */ stack.Push(1); stack.Push(3); stack.Push(2); stack.Push(5); stack.Push(4); -/* Просмотреть верхний элемент */ +/* Доступ к верхнему элементу стека */ int peek = stack.Peek(); -/* Извлечь элемент */ +/* Извлечение элемента из стека */ int pop = stack.Pop(); -/* Получить длину стека */ +/* Получение длины стека */ int size = stack.Count; -/* Проверить, пуст ли стек */ +/* Проверка на пустоту */ bool isEmpty = stack.Count == 0; ``` @@ -101,149 +101,149 @@ bool isEmpty = stack.Count == 0; // В Go рекомендуется использовать Slice как стек var stack []int -/* Поместить элементы в стек */ +/* Помещение элемента в стек */ stack = append(stack, 1) stack = append(stack, 3) stack = append(stack, 2) stack = append(stack, 5) stack = append(stack, 4) -/* Просмотреть верхний элемент */ +/* Доступ к верхнему элементу стека */ peek := stack[len(stack)-1] -/* Извлечь элемент */ +/* Извлечение элемента из стека */ pop := stack[len(stack)-1] stack = stack[:len(stack)-1] -/* Получить длину стека */ +/* Получение длины стека */ size := len(stack) -/* Проверить, пуст ли стек */ +/* Проверка на пустоту */ isEmpty := len(stack) == 0 ``` ```swift title="stack.swift" /* Инициализация стека */ -// В Swift нет встроенного класса стека, поэтому можно использовать Array как стек +// В Swift нет встроенного класса стека, поэтому Array можно использовать как стек var stack: [Int] = [] -/* Поместить элементы в стек */ +/* Помещение элемента в стек */ stack.append(1) stack.append(3) stack.append(2) stack.append(5) stack.append(4) -/* Просмотреть верхний элемент */ +/* Доступ к верхнему элементу стека */ let peek = stack.last! -/* Извлечь элемент */ +/* Извлечение элемента из стека */ let pop = stack.removeLast() -/* Получить длину стека */ +/* Получение длины стека */ let size = stack.count -/* Проверить, пуст ли стек */ +/* Проверка на пустоту */ let isEmpty = stack.isEmpty ``` ```javascript title="stack.js" /* Инициализация стека */ -// В JavaScript нет встроенного класса стека, поэтому можно использовать Array как стек +// В JavaScript нет встроенного класса стека, поэтому Array можно использовать как стек const stack = []; -/* Поместить элементы в стек */ +/* Помещение элемента в стек */ stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* Просмотреть верхний элемент */ -const peek = stack[stack.length-1]; +/* Доступ к верхнему элементу стека */ +const peek = stack[stack.length - 1]; -/* Извлечь элемент */ +/* Извлечение элемента из стека */ const pop = stack.pop(); -/* Получить длину стека */ +/* Получение длины стека */ const size = stack.length; -/* Проверить, пуст ли стек */ -const is_empty = stack.length === 0; +/* Проверка на пустоту */ +const isEmpty = stack.length === 0; ``` ```typescript title="stack.ts" /* Инициализация стека */ -// В TypeScript нет встроенного класса стека, поэтому можно использовать Array как стек +// В TypeScript нет встроенного класса стека, поэтому Array можно использовать как стек const stack: number[] = []; -/* Поместить элементы в стек */ +/* Помещение элемента в стек */ stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* Просмотреть верхний элемент */ +/* Доступ к верхнему элементу стека */ const peek = stack[stack.length - 1]; -/* Извлечь элемент */ +/* Извлечение элемента из стека */ const pop = stack.pop(); -/* Получить длину стека */ +/* Получение длины стека */ const size = stack.length; -/* Проверить, пуст ли стек */ -const is_empty = stack.length === 0; +/* Проверка на пустоту */ +const isEmpty = stack.length === 0; ``` ```dart title="stack.dart" /* Инициализация стека */ -// В Dart нет встроенного класса стека, поэтому можно использовать List как стек -List stack = []; +// В Dart нет встроенного класса стека, поэтому List можно использовать как стек +final List stack = []; -/* Поместить элементы в стек */ +/* Помещение элемента в стек */ stack.add(1); stack.add(3); stack.add(2); stack.add(5); stack.add(4); -/* Просмотреть верхний элемент */ -int peek = stack.last; +/* Доступ к верхнему элементу стека */ +final int peek = stack.last; -/* Извлечь элемент */ -int pop = stack.removeLast(); +/* Извлечение элемента из стека */ +final int pop = stack.removeLast(); -/* Получить длину стека */ -int size = stack.length; +/* Получение длины стека */ +final int size = stack.length; -/* Проверить, пуст ли стек */ -bool isEmpty = stack.isEmpty; +/* Проверка на пустоту */ +final bool isEmpty = stack.isEmpty; ``` ```rust title="stack.rs" -/* Инициализация стека */ -// Используем Vec как стек +// Инициализировать стек +// В Rust рекомендуется использовать Vec как стек let mut stack: Vec = Vec::new(); -/* Поместить элементы в стек */ +// Помещение элемента в стек stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* Просмотреть верхний элемент */ -let top = stack.last().unwrap(); +// Доступ к верхнему элементу стека +let peek = stack.last().unwrap(); -/* Извлечь элемент */ +// Извлечение элемента из стека let pop = stack.pop().unwrap(); -/* Получить длину стека */ +// Получение длины стека let size = stack.len(); -/* Проверить, пуст ли стек */ +// Проверка, пуст ли стек let is_empty = stack.is_empty(); ``` @@ -255,48 +255,48 @@ let is_empty = stack.is_empty(); /* Инициализация стека */ val stack = Stack() -/* Поместить элементы в стек */ +/* Помещение элемента в стек */ stack.push(1) stack.push(3) stack.push(2) stack.push(5) stack.push(4) -/* Просмотреть верхний элемент */ +/* Доступ к верхнему элементу стека */ val peek = stack.peek() -/* Извлечь элемент */ +/* Извлечение элемента из стека */ val pop = stack.pop() -/* Получить длину стека */ +/* Получение длины стека */ val size = stack.size -/* Проверить, пуст ли стек */ +/* Проверка на пустоту */ val isEmpty = stack.isEmpty() ``` ```ruby title="stack.rb" -# Инициализация стека -# В Ruby нет встроенного класса стека, поэтому можно использовать Array как стек +# Инициализировать стек +# В Ruby нет встроенного класса стека, поэтому Array можно использовать как стек stack = [] -# Поместить элементы в стек +# Помещение элемента в стек stack << 1 stack << 3 stack << 2 stack << 5 stack << 4 -# Просмотреть верхний элемент +# Доступ к верхнему элементу стека peek = stack.last -# Извлечь элемент +# Извлечение элемента из стека pop = stack.pop -# Получить длину стека +# Получение длины стека size = stack.length -# Проверить, пуст ли стек +# Проверка на пустоту is_empty = stack.empty? ``` diff --git a/ru/codes/snippets/chapter_tree/binary_tree.md b/ru/codes/snippets/chapter_tree/binary_tree.md index bc9c2bf15..db67acacc 100644 --- a/ru/codes/snippets/chapter_tree/binary_tree.md +++ b/ru/codes/snippets/chapter_tree/binary_tree.md @@ -4,16 +4,16 @@ class TreeNode: """Класс узла двоичного дерева""" def __init__(self, val: int): self.val: int = val # Значение узла - self.left: TreeNode | None = None # Ссылка на левого дочернего узла - self.right: TreeNode | None = None # Ссылка на правого дочернего узла + self.left: TreeNode | None = None # Ссылка на левый дочерний узел + self.right: TreeNode | None = None # Ссылка на правый дочерний узел ``` ```cpp title="" /* Структура узла двоичного дерева */ struct TreeNode { int val; // Значение узла - TreeNode *left; // Указатель на левого дочернего узла - TreeNode *right; // Указатель на правого дочернего узла + TreeNode *left; // Указатель на левый дочерний узел + TreeNode *right; // Указатель на правый дочерний узел TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; ``` @@ -22,8 +22,8 @@ struct TreeNode { /* Класс узла двоичного дерева */ class TreeNode { int val; // Значение узла - TreeNode left; // Ссылка на левого дочернего узла - TreeNode right; // Ссылка на правого дочернего узла + TreeNode left; // Ссылка на левый дочерний узел + TreeNode right; // Ссылка на правый дочерний узел TreeNode(int x) { val = x; } } ``` @@ -32,8 +32,8 @@ class TreeNode { /* Класс узла двоичного дерева */ class TreeNode(int? x) { public int? val = x; // Значение узла - public TreeNode? left; // Ссылка на левого дочернего узла - public TreeNode? right; // Ссылка на правого дочернего узла + public TreeNode? left; // Ссылка на левый дочерний узел + public TreeNode? right; // Ссылка на правый дочерний узел } ``` @@ -47,8 +47,8 @@ type TreeNode struct { /* Конструктор */ func NewTreeNode(v int) *TreeNode { return &TreeNode{ - Left: nil, // Указатель на левого дочернего узла - Right: nil, // Указатель на правого дочернего узла + Left: nil, // Указатель на левый дочерний узел + Right: nil, // Указатель на правый дочерний узел Val: v, // Значение узла } } @@ -58,8 +58,8 @@ func NewTreeNode(v int) *TreeNode { /* Класс узла двоичного дерева */ class TreeNode { var val: Int // Значение узла - var left: TreeNode? // Ссылка на левого дочернего узла - var right: TreeNode? // Ссылка на правого дочернего узла + var left: TreeNode? // Ссылка на левый дочерний узел + var right: TreeNode? // Ссылка на правый дочерний узел init(x: Int) { val = x @@ -71,8 +71,8 @@ class TreeNode { /* Класс узла двоичного дерева */ class TreeNode { val; // Значение узла - left; // Указатель на левого дочернего узла - right; // Указатель на правого дочернего узла + left; // Указатель на левый дочерний узел + right; // Указатель на правый дочерний узел constructor(val, left, right) { this.val = val === undefined ? 0 : val; this.left = left === undefined ? null : left; @@ -90,8 +90,8 @@ class TreeNode { constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { this.val = val === undefined ? 0 : val; // Значение узла - this.left = left === undefined ? null : left; // Ссылка на левого дочернего узла - this.right = right === undefined ? null : right; // Ссылка на правого дочернего узла + this.left = left === undefined ? null : left; // Ссылка на левый дочерний узел + this.right = right === undefined ? null : right; // Ссылка на правый дочерний узел } } ``` @@ -100,8 +100,8 @@ class TreeNode { /* Класс узла двоичного дерева */ class TreeNode { int val; // Значение узла - TreeNode? left; // Ссылка на левого дочернего узла - TreeNode? right; // Ссылка на правого дочернего узла + TreeNode? left; // Ссылка на левый дочерний узел + TreeNode? right; // Ссылка на правый дочерний узел TreeNode(this.val, [this.left, this.right]); } ``` @@ -113,8 +113,8 @@ use std::cell::RefCell; /* Структура узла двоичного дерева */ struct TreeNode { val: i32, // Значение узла - left: Option>>, // Ссылка на левого дочернего узла - right: Option>>, // Ссылка на правого дочернего узла + left: Option>>, // Ссылка на левый дочерний узел + right: Option>>, // Ссылка на правый дочерний узел } impl TreeNode { @@ -133,9 +133,8 @@ impl TreeNode { /* Структура узла двоичного дерева */ typedef struct TreeNode { int val; // Значение узла - int height; // Высота узла - struct TreeNode *left; // Указатель на левого дочернего узла - struct TreeNode *right; // Указатель на правого дочернего узла + struct TreeNode *left; // Указатель на левый дочерний узел + struct TreeNode *right; // Указатель на правый дочерний узел } TreeNode; /* Конструктор */ @@ -144,7 +143,6 @@ TreeNode *newTreeNode(int val) { node = (TreeNode *)malloc(sizeof(TreeNode)); node->val = val; - node->height = 0; node->left = NULL; node->right = NULL; return node; @@ -154,8 +152,8 @@ TreeNode *newTreeNode(int val) { ```kotlin title="" /* Класс узла двоичного дерева */ class TreeNode(val _val: Int) { // Значение узла - var left: TreeNode? = null // Ссылка на левого дочернего узла - var right: TreeNode? = null // Ссылка на правого дочернего узла + var left: TreeNode? = null // Ссылка на левый дочерний узел + var right: TreeNode? = null // Ссылка на правый дочерний узел } ``` @@ -163,8 +161,8 @@ class TreeNode(val _val: Int) { // Значение узла ### Класс узла двоичного дерева ### class TreeNode attr_accessor :val # Значение узла - attr_accessor :left # Ссылка на левого дочернего узла - attr_accessor :right # Ссылка на правого дочернего узла + attr_accessor :left # Ссылка на левый дочерний узел + attr_accessor :right # Ссылка на правый дочерний узел def initialize(val) @val = val @@ -181,7 +179,7 @@ n2 = TreeNode(val=2) n3 = TreeNode(val=3) n4 = TreeNode(val=4) n5 = TreeNode(val=5) -# Построение ссылок (указателей) между узлами +# Построить связи между узлами (указатели) n1.left = n2 n1.right = n3 n2.left = n4 @@ -190,13 +188,13 @@ n2.right = n5 ```cpp title="binary_tree.cpp" /* Инициализация двоичного дерева */ -// Инициализация узлов -TreeNode* n1 = new TreeNode(1); -TreeNode* n2 = new TreeNode(2); -TreeNode* n3 = new TreeNode(3); -TreeNode* n4 = new TreeNode(4); -TreeNode* n5 = new TreeNode(5); -// Построение ссылок (указателей) между узлами +// Инициализация узла +TreeNode *n1 = new TreeNode(1); +TreeNode *n2 = new TreeNode(2); +TreeNode *n3 = new TreeNode(3); +TreeNode *n4 = new TreeNode(4); +TreeNode *n5 = new TreeNode(5); +// Построить связи между узлами (указатели) n1->left = n2; n1->right = n3; n2->left = n4; @@ -204,13 +202,14 @@ n2->right = n5; ``` ```java title="binary_tree.java" -// Инициализация узлов +/* Инициализация двоичного дерева */ +// Инициализация узла TreeNode n1 = new TreeNode(1); TreeNode n2 = new TreeNode(2); TreeNode n3 = new TreeNode(3); TreeNode n4 = new TreeNode(4); TreeNode n5 = new TreeNode(5); -// Построение ссылок (указателей) между узлами +// Построить связи между узлами (указатели) n1.left = n2; n1.right = n3; n2.left = n4; @@ -219,13 +218,13 @@ n2.right = n5; ```csharp title="binary_tree.cs" /* Инициализация двоичного дерева */ -// Инициализация узлов +// Инициализация узла TreeNode n1 = new(1); TreeNode n2 = new(2); TreeNode n3 = new(3); TreeNode n4 = new(4); TreeNode n5 = new(5); -// Построение ссылок (указателей) между узлами +// Построить связи между узлами (указатели) n1.left = n2; n1.right = n3; n2.left = n4; @@ -234,13 +233,13 @@ n2.right = n5; ```go title="binary_tree.go" /* Инициализация двоичного дерева */ -// Инициализация узлов +// Инициализация узла n1 := NewTreeNode(1) n2 := NewTreeNode(2) n3 := NewTreeNode(3) n4 := NewTreeNode(4) n5 := NewTreeNode(5) -// Построение ссылок (указателей) между узлами +// Построить связи между узлами (указатели) n1.Left = n2 n1.Right = n3 n2.Left = n4 @@ -248,13 +247,14 @@ n2.Right = n5 ``` ```swift title="binary_tree.swift" -// Инициализация узлов +/* Инициализация двоичного дерева */ +// Инициализация узла let n1 = TreeNode(x: 1) let n2 = TreeNode(x: 2) let n3 = TreeNode(x: 3) let n4 = TreeNode(x: 4) let n5 = TreeNode(x: 5) -// Построение ссылок (указателей) между узлами +// Построить связи между узлами (указатели) n1.left = n2 n1.right = n3 n2.left = n4 @@ -263,13 +263,13 @@ n2.right = n5 ```javascript title="binary_tree.js" /* Инициализация двоичного дерева */ -// Инициализация узлов +// Инициализация узла let n1 = new TreeNode(1), n2 = new TreeNode(2), n3 = new TreeNode(3), n4 = new TreeNode(4), n5 = new TreeNode(5); -// Построение ссылок (указателей) между узлами +// Построить связи между узлами (указатели) n1.left = n2; n1.right = n3; n2.left = n4; @@ -278,13 +278,13 @@ n2.right = n5; ```typescript title="binary_tree.ts" /* Инициализация двоичного дерева */ -// Инициализация узлов +// Инициализация узла let n1 = new TreeNode(1), n2 = new TreeNode(2), n3 = new TreeNode(3), n4 = new TreeNode(4), n5 = new TreeNode(5); -// Построение ссылок (указателей) между узлами +// Построить связи между узлами (указатели) n1.left = n2; n1.right = n3; n2.left = n4; @@ -294,12 +294,12 @@ n2.right = n5; ```dart title="binary_tree.dart" /* Инициализация двоичного дерева */ // Инициализация узлов -TreeNode n1 = new TreeNode(1); -TreeNode n2 = new TreeNode(2); -TreeNode n3 = new TreeNode(3); -TreeNode n4 = new TreeNode(4); -TreeNode n5 = new TreeNode(5); -// Построение ссылок (указателей) между узлами +TreeNode n1 = TreeNode(1); +TreeNode n2 = TreeNode(2); +TreeNode n3 = TreeNode(3); +TreeNode n4 = TreeNode(4); +TreeNode n5 = TreeNode(5); +// Построить связи между узлами (указатели) n1.left = n2; n1.right = n3; n2.left = n4; @@ -307,28 +307,29 @@ n2.right = n5; ``` ```rust title="binary_tree.rs" -// Инициализация узлов +/* Инициализация двоичного дерева */ +// Инициализация узла let n1 = TreeNode::new(1); let n2 = TreeNode::new(2); let n3 = TreeNode::new(3); let n4 = TreeNode::new(4); let n5 = TreeNode::new(5); -// Построение ссылок (указателей) между узлами -n1.borrow_mut().left = Some(n2.clone()); -n1.borrow_mut().right = Some(n3); -n2.borrow_mut().left = Some(n4); -n2.borrow_mut().right = Some(n5); +// Построить связи между узлами (указатели) +n1.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().right = Some(Rc::clone(&n3)); +n2.borrow_mut().left = Some(Rc::clone(&n4)); +n2.borrow_mut().right = Some(Rc::clone(&n5)); ``` ```c title="binary_tree.c" /* Инициализация двоичного дерева */ -// Инициализация узлов +// Инициализация узла TreeNode *n1 = newTreeNode(1); TreeNode *n2 = newTreeNode(2); TreeNode *n3 = newTreeNode(3); TreeNode *n4 = newTreeNode(4); TreeNode *n5 = newTreeNode(5); -// Построение ссылок (указателей) между узлами +// Построить связи между узлами (указатели) n1->left = n2; n1->right = n3; n2->left = n4; @@ -336,13 +337,14 @@ n2->right = n5; ``` ```kotlin title="binary_tree.kt" -// Инициализация узлов +/* Инициализация двоичного дерева */ +// Инициализация узла val n1 = TreeNode(1) val n2 = TreeNode(2) val n3 = TreeNode(3) val n4 = TreeNode(4) val n5 = TreeNode(5) -// Построение ссылок (указателей) между узлами +// Построить связи между узлами (указатели) n1.left = n2 n1.right = n3 n2.left = n4 @@ -357,7 +359,7 @@ n2 = TreeNode.new(2) n3 = TreeNode.new(3) n4 = TreeNode.new(4) n5 = TreeNode.new(5) -# Построение ссылок (указателей) между узлами +# Построить связи между узлами (указатели) n1.left = n2 n1.right = n3 n2.left = n4 @@ -370,27 +372,27 @@ https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%2 ```python title="binary_tree.py" # Вставка и удаление узлов -p = TreeNode(0) +P = TreeNode(0) # Вставить узел P между n1 -> n2 -n1.left = p -p.left = n2 +n1.left = P +P.left = n2 # Удалить узел P n1.left = n2 ``` ```cpp title="binary_tree.cpp" /* Вставка и удаление узлов */ -TreeNode* P = new TreeNode(0); +TreeNode *P = new TreeNode(0); // Вставить узел P между n1 -> n2 n1->left = P; P->left = n2; // Удалить узел P n1->left = n2; -// Освободить память -delete P; +delete P; // Освободить память ``` ```java title="binary_tree.java" +/* Вставка и удаление узлов */ TreeNode P = new TreeNode(0); // Вставить узел P между n1 -> n2 n1.left = P; @@ -420,6 +422,7 @@ n1.Left = n2 ``` ```swift title="binary_tree.swift" +/* Вставка и удаление узлов */ let P = TreeNode(x: 0) // Вставить узел P между n1 -> n2 n1.left = P @@ -430,7 +433,7 @@ n1.left = n2 ```javascript title="binary_tree.js" /* Вставка и удаление узлов */ -let P = new TreeNode(0); +const P = new TreeNode(0); // Вставить узел P между n1 -> n2 n1.left = P; P.left = n2; @@ -450,21 +453,23 @@ n1.left = n2; ```dart title="binary_tree.dart" /* Вставка и удаление узлов */ -TreeNode P = new TreeNode(0); +TreeNode p = TreeNode(0); // Вставить узел P между n1 -> n2 -n1.left = P; -P.left = n2; +n1.left = p; +p.left = n2; // Удалить узел P n1.left = n2; ``` ```rust title="binary_tree.rs" +/* Вставка и удаление узлов */ let p = TreeNode::new(0); // Вставить узел P между n1 -> n2 -n1.borrow_mut().left = Some(p.clone()); -p.borrow_mut().left = Some(n2.clone()); -// Удалить узел p -n1.borrow_mut().left = Some(n2); +p.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().left = Some(Rc::clone(&p)); +// Удалить узел P +drop(p); +n1.borrow_mut().left = Some(Rc::clone(&n2)); ``` ```c title="binary_tree.c" @@ -480,6 +485,7 @@ free(P); ``` ```kotlin title="binary_tree.kt" +/* Вставка и удаление узлов */ val P = TreeNode(0) // Вставить узел P между n1 -> n2 n1.left = P @@ -494,9 +500,9 @@ _p = TreeNode.new(0) # Вставить узел _p между n1 -> n2 n1.left = _p _p.left = n2 -# Удалить узел +# Удаление узла n1.left = n2 ``` -https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%D0%9A%D0%BB%D0%B0%D1%81%D1%81%20%D1%83%D0%B7%D0%BB%D0%B0%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B3%D0%BE%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%B0%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BB%D0%B5%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BF%D1%80%D0%B0%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B5%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%BE%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%D0%9F%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B8%D1%82%D1%8C%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20%D1%83%D0%B7%D0%BB%D0%B0%D0%BC%D0%B8%20%28%D1%83%D0%BA%D0%B0%D0%B7%D0%B0%D1%82%D0%B5%D0%BB%D0%B8%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%BA%D0%B0%20%D0%B8%20%D1%83%D0%B4%D0%B0%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%BE%D0%B2%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%20P%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20n1%20-%3E%20n2%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%D0%9A%D0%BB%D0%B0%D1%81%D1%81%20%D1%83%D0%B7%D0%BB%D0%B0%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B3%D0%BE%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%B0%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%D0%97%D0%BD%D0%B0%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%B0%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BB%D0%B5%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%D0%A1%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%20%D0%BD%D0%B0%20%D0%BF%D1%80%D0%B0%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D1%87%D0%B5%D1%80%D0%BD%D0%B8%D0%B9%20%D1%83%D0%B7%D0%B5%D0%BB%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%B4%D0%B2%D0%BE%D0%B8%D1%87%D0%BD%D0%BE%D0%B5%20%D0%B4%D0%B5%D1%80%D0%B5%D0%B2%D0%BE%0A%20%20%20%20%23%20%D0%98%D0%BD%D0%B8%D1%86%D0%B8%D0%B0%D0%BB%D0%B8%D0%B7%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%D0%9F%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B8%D1%82%D1%8C%20%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20%D1%83%D0%B7%D0%BB%D0%B0%D0%BC%D0%B8%20%28%D1%83%D0%BA%D0%B0%D0%B7%D0%B0%D1%82%D0%B5%D0%BB%D0%B8%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%BA%D0%B0%20%D0%B8%20%D1%83%D0%B4%D0%B0%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%20%D1%83%D0%B7%D0%BB%D0%BE%D0%B2%0A%20%20%20%20P%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%D0%92%D1%81%D1%82%D0%B0%D0%B2%D0%B8%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%20P%20%D0%BC%D0%B5%D0%B6%D0%B4%D1%83%20n1%20-%3E%20n2%0A%20%20%20%20n1.left%20%3D%20P%0A%20%20%20%20P.left%20%3D%20n2%0A%20%20%20%20%23%20%D0%A3%D0%B4%D0%B0%D0%BB%D0%B8%D1%82%D1%8C%20%D1%83%D0%B7%D0%B5%D0%BB%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/ru/codes/swift/chapter_stack_and_queue/deque.swift b/ru/codes/swift/chapter_stack_and_queue/deque.swift index f5aa48207..5e2f96538 100644 --- a/ru/codes/swift/chapter_stack_and_queue/deque.swift +++ b/ru/codes/swift/chapter_stack_and_queue/deque.swift @@ -27,7 +27,7 @@ enum Deque { print("Последний элемент peekLast = \(peekLast)") /* Извлечение элемента из очереди */ - // При использовании Array для имитации popFirst имеет сложность O(n) + // При использовании Array для имитации removeFirst имеет сложность O(n) let popFirst = deque.removeFirst() print("Извлеченный из головы элемент popFirst = \(popFirst), deque после извлечения из головы = \(deque)") let popLast = deque.removeLast() diff --git a/ru/codes/swift/chapter_stack_and_queue/queue.swift b/ru/codes/swift/chapter_stack_and_queue/queue.swift index 1522bfc41..5f26af8c2 100644 --- a/ru/codes/swift/chapter_stack_and_queue/queue.swift +++ b/ru/codes/swift/chapter_stack_and_queue/queue.swift @@ -25,7 +25,7 @@ enum Queue { print("Первый элемент peek = \(peek)") /* Извлечение элемента из очереди */ - // При использовании Array для имитации pop имеет сложность O(n) + // При использовании Array для имитации removeFirst имеет сложность O(n) let pop = queue.removeFirst() print("Извлеченный элемент pop = \(pop), queue после извлечения = \(queue)") diff --git a/ru/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts b/ru/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts index b3cb2ebfd..4acb279c0 100644 --- a/ru/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/ru/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -6,8 +6,8 @@ /* Узел двусвязного списка */ class ListNode { - prev: ListNode; // Ссылка на узел-предшественник (указатель) - next: ListNode; // Ссылка на узел-преемник (указатель) + prev: ListNode | null; // Ссылка на узел-предшественник (указатель) + next: ListNode | null; // Ссылка на узел-преемник (указатель) val: number; // Значение узла constructor(val: number) { diff --git a/zh-hant/codes/c/chapter_array_and_linkedlist/array.c b/zh-hant/codes/c/chapter_array_and_linkedlist/array.c index 0cba2f085..1d6358c0a 100644 --- a/zh-hant/codes/c/chapter_array_and_linkedlist/array.c +++ b/zh-hant/codes/c/chapter_array_and_linkedlist/array.c @@ -75,7 +75,7 @@ int main() { /* 初始化陣列 */ int size = 5; - int arr[5]; + int arr[5] = {0}; printf("陣列 arr = "); printArray(arr, size); diff --git a/zh-hant/codes/c/chapter_stack_and_queue/linkedlist_deque.c b/zh-hant/codes/c/chapter_stack_and_queue/linkedlist_deque.c index 2cdd7b9ee..c326f4e83 100644 --- a/zh-hant/codes/c/chapter_stack_and_queue/linkedlist_deque.c +++ b/zh-hant/codes/c/chapter_stack_and_queue/linkedlist_deque.c @@ -182,7 +182,7 @@ int main() { int peekFirstNum = peekFirst(deque); printf("佇列首元素 peekFirst = %d\r\n", peekFirstNum); int peekLastNum = peekLast(deque); - printf("佇列首元素 peekLast = %d\r\n", peekLastNum); + printf("佇列尾元素 peekLast = %d\r\n", peekLastNum); /* 元素入列 */ pushLast(deque, 4); diff --git a/zh-hant/codes/c/utils/list_node.h b/zh-hant/codes/c/utils/list_node.h index 73567a1bc..a730865cf 100644 --- a/zh-hant/codes/c/utils/list_node.h +++ b/zh-hant/codes/c/utils/list_node.h @@ -14,7 +14,7 @@ extern "C" { /* 鏈結串列節點結構體 */ typedef struct ListNode { int val; // 節點值 - struct ListNode *next; // 指向下一節點的引用 + struct ListNode *next; // 指向下一節點的指標 } ListNode; /* 建構子,初始化一個新節點 */ diff --git a/zh-hant/codes/cpp/chapter_array_and_linkedlist/array.cpp b/zh-hant/codes/cpp/chapter_array_and_linkedlist/array.cpp index 89d3f20b5..b055c8565 100644 --- a/zh-hant/codes/cpp/chapter_array_and_linkedlist/array.cpp +++ b/zh-hant/codes/cpp/chapter_array_and_linkedlist/array.cpp @@ -18,7 +18,7 @@ int randomAccess(int *nums, int size) { /* 擴展陣列長度 */ int *extend(int *nums, int size, int enlarge) { // 初始化一個擴展長度後的陣列 - int *res = new int[size + enlarge]; + int *res = new int[size + enlarge]{}; // 將原陣列中的所有元素複製到新陣列 for (int i = 0; i < size; i++) { res[i] = nums[i]; @@ -69,7 +69,7 @@ int find(int *nums, int size, int target) { int main() { /* 初始化陣列 */ int size = 5; - int *arr = new int[size]; + int *arr = new int[size]{}; cout << "陣列 arr = "; printArray(arr, size); diff --git a/zh-hant/codes/dart/chapter_hashing/hash_map.dart b/zh-hant/codes/dart/chapter_hashing/hash_map.dart index 9bcec5da5..dbe1f4ef8 100644 --- a/zh-hant/codes/dart/chapter_hashing/hash_map.dart +++ b/zh-hant/codes/dart/chapter_hashing/hash_map.dart @@ -36,6 +36,5 @@ void main() { print("\n單獨走訪鍵 Key"); map.keys.forEach((key) => print(key)); print("\n單獨走訪值 Value"); - map.forEach((key, value) => print("$value")); map.values.forEach((value) => print(value)); } diff --git a/zh-hant/codes/dart/chapter_tree/binary_tree.dart b/zh-hant/codes/dart/chapter_tree/binary_tree.dart index 4cdbfaacb..c14e4f7a9 100644 --- a/zh-hant/codes/dart/chapter_tree/binary_tree.dart +++ b/zh-hant/codes/dart/chapter_tree/binary_tree.dart @@ -9,7 +9,7 @@ import '../utils/tree_node.dart'; void main() { /* 初始化二元樹 */ - // 舒適化節點 + // 初始化節點 TreeNode n1 = TreeNode(1); TreeNode n2 = TreeNode(2); TreeNode n3 = TreeNode(3); diff --git a/zh-hant/codes/go/chapter_heap/heap_test.go b/zh-hant/codes/go/chapter_heap/heap_test.go index 3fb6e1ae4..eee2f608d 100644 --- a/zh-hant/codes/go/chapter_heap/heap_test.go +++ b/zh-hant/codes/go/chapter_heap/heap_test.go @@ -91,8 +91,6 @@ func TestMyHeap(t *testing.T) { } func TestTopKHeap(t *testing.T) { - /* 初始化堆積 */ - // 初始化大頂堆積 nums := []int{1, 7, 6, 3, 2} k := 3 res := topKHeap(nums, k) diff --git a/zh-hant/codes/go/chapter_stack_and_queue/deque_test.go b/zh-hant/codes/go/chapter_stack_and_queue/deque_test.go index 37e60e80e..0f843d018 100644 --- a/zh-hant/codes/go/chapter_stack_and_queue/deque_test.go +++ b/zh-hant/codes/go/chapter_stack_and_queue/deque_test.go @@ -51,7 +51,6 @@ func TestDeque(t *testing.T) { func TestArrayDeque(t *testing.T) { /* 初始化雙向佇列 */ - // 在 Go 中,將 list 作為雙向佇列使用 deque := newArrayDeque(16) /* 元素入列 */ @@ -102,7 +101,7 @@ func TestLinkedListDeque(t *testing.T) { deque.pushLast(4) deque.pushFirst(3) deque.pushFirst(1) - fmt.Print("佇列 deque = ") + fmt.Print("雙向佇列 deque = ") PrintList(deque.toList()) // 訪問佇列首元素 diff --git a/zh-hant/codes/go/chapter_stack_and_queue/queue_test.go b/zh-hant/codes/go/chapter_stack_and_queue/queue_test.go index 8eca50e4b..d42695aa7 100644 --- a/zh-hant/codes/go/chapter_stack_and_queue/queue_test.go +++ b/zh-hant/codes/go/chapter_stack_and_queue/queue_test.go @@ -84,7 +84,7 @@ func TestArrayQueue(t *testing.T) { for i := 0; i < 10; i++ { queue.push(i) queue.pop() - fmt.Print("第", i, "輪入列 + 出列後 queue =") + fmt.Print("第 ", i, " 輪入列 + 出列後 queue =") PrintSlice(queue.toSlice()) } } diff --git a/zh-hant/codes/java/chapter_array_and_linkedlist/list.java b/zh-hant/codes/java/chapter_array_and_linkedlist/list.java index 13862233b..a4945c7fe 100644 --- a/zh-hant/codes/java/chapter_array_and_linkedlist/list.java +++ b/zh-hant/codes/java/chapter_array_and_linkedlist/list.java @@ -11,7 +11,7 @@ import java.util.*; public class list { public static void main(String[] args) { /* 初始化串列 */ - // 注意陣列的元素型別是 int[] 的包裝類別 Integer[] + // 注意陣列型別需為 Integer[] 而非 int[],因為串列元素只能是 int 的包裝類別 Integer Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); System.out.println("串列 nums = " + nums); diff --git a/zh-hant/codes/python/chapter_hashing/built_in_hash.py b/zh-hant/codes/python/chapter_hashing/built_in_hash.py index 31258b421..472d64919 100644 --- a/zh-hant/codes/python/chapter_hashing/built_in_hash.py +++ b/zh-hant/codes/python/chapter_hashing/built_in_hash.py @@ -30,7 +30,7 @@ if __name__ == "__main__": tup = (12836, "小哈") hash_tup = hash(tup) - print(f"元組 {tup} 的雜湊值為 {hash(hash_tup)}") + print(f"元組 {tup} 的雜湊值為 {hash_tup}") obj = ListNode(0) hash_obj = hash(obj) diff --git a/zh-hant/codes/ruby/chapter_hashing/built_in_hash.rb b/zh-hant/codes/ruby/chapter_hashing/built_in_hash.rb index 28b33f42a..bb6a0d3cb 100644 --- a/zh-hant/codes/ruby/chapter_hashing/built_in_hash.rb +++ b/zh-hant/codes/ruby/chapter_hashing/built_in_hash.rb @@ -24,9 +24,9 @@ if __FILE__ == $0 hash_str = str.hash puts "字串 #{str} 的雜湊值為 #{hash_str}" - tup = [12836, '小哈'] - hash_tup = tup.hash - puts "元組 #{tup} 的雜湊值為 #{hash_tup}" + arr = [12836, '小哈'] + hash_arr = arr.hash + puts "陣列 #{arr} 的雜湊值為 #{hash_arr}" obj = ListNode.new(0) hash_obj = obj.hash diff --git a/zh-hant/codes/ruby/chapter_stack_and_queue/array_deque.rb b/zh-hant/codes/ruby/chapter_stack_and_queue/array_deque.rb index f06ba0ee4..28df0b75f 100644 --- a/zh-hant/codes/ruby/chapter_stack_and_queue/array_deque.rb +++ b/zh-hant/codes/ruby/chapter_stack_and_queue/array_deque.rb @@ -127,13 +127,13 @@ if __FILE__ == $0 deque.push_last(4) puts "元素 4 佇列尾入列後 deque = #{deque.to_array}" deque.push_first(1) - puts "元素 1 佇列尾入列後 deque = #{deque.to_array}" + puts "元素 1 佇列首入列後 deque = #{deque.to_array}" # 元素出列 pop_last = deque.pop_last puts "佇列尾出列元素 = #{pop_last},佇列尾出列後 deque = #{deque.to_array}" pop_first = deque.pop_first - puts "佇列尾出列元素 = #{pop_first},佇列尾出列後 deque = #{deque.to_array}" + puts "佇列首出列元素 = #{pop_first},佇列首出列後 deque = #{deque.to_array}" # 獲取雙向佇列的長度 size = deque.size diff --git a/zh-hant/codes/ruby/chapter_stack_and_queue/deque.rb b/zh-hant/codes/ruby/chapter_stack_and_queue/deque.rb index 980bcace8..06516b7cf 100644 --- a/zh-hant/codes/ruby/chapter_stack_and_queue/deque.rb +++ b/zh-hant/codes/ruby/chapter_stack_and_queue/deque.rb @@ -7,10 +7,10 @@ Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) ### Driver Code ### if __FILE__ == $0 # 初始化雙向佇列 - # Ruby 沒有內直的雙端佇列,只能把 Array 當作雙端佇列來使用 + # Ruby 沒有內建的雙端佇列,只能把 Array 當作雙端佇列來使用 deque = [] - # 元素如隊 + # 元素入列 deque << 2 deque << 5 deque << 4 @@ -26,7 +26,7 @@ if __FILE__ == $0 puts "佇列尾元素 peek_last = #{peek_last}" # 元素出列 - # 請注意,由於是陣列, Array#shift 方法的時間複雜度為 O(n) + # 請注意,由於是陣列,Array#shift 方法的時間複雜度為 O(n) pop_front = deque.shift puts "佇列首出列元素 pop_front = #{pop_front},佇列首出列後 deque = #{deque}" pop_back = deque.pop diff --git a/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb b/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb index 66a9cee9e..631fb6aff 100644 --- a/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,11 +4,11 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end -### 雙向鏈結串列節點 +### 雙向鏈結串列節點 ### class ListNode attr_accessor :val attr_accessor :next # 後繼節點引用 - attr_accessor :prev # 前軀節點引用 + attr_accessor :prev # 前驅節點引用 ### 建構子 ### def initialize(val) @@ -101,7 +101,7 @@ class LinkedListDeque pop(true) end - ### 佇列首出列 ### + ### 佇列尾出列 ### def pop_last pop(false) end @@ -145,7 +145,7 @@ if __FILE__ == $0 peek_first = deque.peek_first puts "佇列首元素 peek_first = #{peek_first}" peek_last = deque.peek_last - puts "佇列首元素 peek_last = #{peek_last}" + puts "佇列尾元素 peek_last = #{peek_last}" # 元素入列 deque.push_last(4) diff --git a/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb b/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb index dd0aa135d..6e38b330b 100644 --- a/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb +++ b/zh-hant/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb @@ -74,7 +74,7 @@ if __FILE__ == $0 # 初始化佇列 queue = LinkedListQueue.new - # 元素如隊 + # 元素入列 queue.push(1) queue.push(3) queue.push(2) diff --git a/zh-hant/codes/ruby/chapter_stack_and_queue/queue.rb b/zh-hant/codes/ruby/chapter_stack_and_queue/queue.rb index bb3b0ab23..6f84a14ac 100644 --- a/zh-hant/codes/ruby/chapter_stack_and_queue/queue.rb +++ b/zh-hant/codes/ruby/chapter_stack_and_queue/queue.rb @@ -7,7 +7,7 @@ Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) ### Driver Code ### if __FILE__ == $0 # 初始化佇列 - # Ruby 內建的佇列(Thread::Queue) 沒有 peek 和走訪方法,可以把 Array 當作佇列來使用 + # Ruby 內建的佇列(Thread::Queue)沒有 peek 和走訪方法,可以把 Array 當作佇列來使用 queue = [] # 元素入列 @@ -23,7 +23,7 @@ if __FILE__ == $0 puts "佇列首元素 peek = #{peek}" # 元素出列 - # 清注意,由於是陣列,Array#shift 方法時間複雜度為 O(n) + # 請注意,由於是陣列,Array#shift 方法的時間複雜度為 O(n) pop = queue.shift puts "出列元素 pop = #{pop}" puts "出列後 queue = #{queue}" diff --git a/zh-hant/codes/rust/chapter_hashing/build_in_hash.rs b/zh-hant/codes/rust/chapter_hashing/build_in_hash.rs index f4dee23bd..cd74117e8 100644 --- a/zh-hant/codes/rust/chapter_hashing/build_in_hash.rs +++ b/zh-hant/codes/rust/chapter_hashing/build_in_hash.rs @@ -45,5 +45,5 @@ fn main() { let mut hasher = DefaultHasher::new(); node.borrow().val.hash(&mut hasher); let hash = hasher.finish(); - println!("節點物件 {:?} 的雜湊值為{}", node, hash); + println!("節點物件 {:?} 的雜湊值為 {}", node, hash); } diff --git a/zh-hant/codes/rust/chapter_stack_and_queue/stack.rs b/zh-hant/codes/rust/chapter_stack_and_queue/stack.rs index 83f895c71..9355535dd 100644 --- a/zh-hant/codes/rust/chapter_stack_and_queue/stack.rs +++ b/zh-hant/codes/rust/chapter_stack_and_queue/stack.rs @@ -9,7 +9,7 @@ use hello_algo_rust::include::print_util; /* Driver Code */ pub fn main() { // 初始化堆疊 - // 在 rust 中,推薦將 Vec 當作堆疊來使用 + // 在 Rust 中,推薦將 Vec 當作堆疊來使用 let mut stack: Vec = Vec::new(); // 元素入堆疊 diff --git a/zh-hant/codes/snippets/chapter_array_and_linkedlist/array.md b/zh-hant/codes/snippets/chapter_array_and_linkedlist/array.md index 482b522ce..daad3736f 100644 --- a/zh-hant/codes/snippets/chapter_array_and_linkedlist/array.md +++ b/zh-hant/codes/snippets/chapter_array_and_linkedlist/array.md @@ -9,10 +9,10 @@ nums: list[int] = [1, 3, 2, 5, 4] /* 初始化陣列 */ // 儲存在堆疊上 int arr[5] = {}; -int nums[5] = { 1, 3, 2, 5, 4 }; +int nums[5] = {1, 3, 2, 5, 4}; // 儲存在堆積上(需要手動釋放空間) -int* arr1 = new int[5] {}; -int* nums1 = new int[5] { 1, 3, 2, 5, 4 }; +int *arr1 = new int[5]{}; +int *nums1 = new int[5]{1, 3, 2, 5, 4}; ``` ```java title="array.java" @@ -22,7 +22,7 @@ int[] nums = { 1, 3, 2, 5, 4 }; ``` ```csharp title="array.cs" -/* 初始化陣列 */ +// 初始化陣列 int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ] int[] nums = [1, 3, 2, 5, 4]; ``` @@ -32,38 +32,37 @@ int[] nums = [1, 3, 2, 5, 4]; var arr [5]int // 在 Go 中,指定長度時([5]int)為陣列,不指定長度時([]int)為切片 // 由於 Go 的陣列被設計為在編譯期確定長度,因此只能使用常數來指定長度 -// 為了方便實現擴容 extend() 方法,以下將切片(Slice)看作陣列(Array) +// 為了方便實現擴容 extend() 函式,以下將切片(Slice)看作陣列(Array) nums := []int{1, 3, 2, 5, 4} ``` ```swift title="array.swift" /* 初始化陣列 */ let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0] -let nums = [1, 3, 2, 5, 4] +var nums = [1, 3, 2, 5, 4] ``` ```javascript title="array.js" /* 初始化陣列 */ -var arr = new Array(5).fill(0); -var nums = [1, 3, 2, 5, 4]; +const arr = new Array(5).fill(0); +let nums = [1, 3, 2, 5, 4]; ``` ```typescript title="array.ts" /* 初始化陣列 */ -let arr: number[] = new Array(5).fill(0); +const arr: number[] = new Array(5).fill(0); let nums: number[] = [1, 3, 2, 5, 4]; ``` ```dart title="array.dart" /* 初始化陣列 */ -List arr = List.filled(5, 0); // [0, 0, 0, 0, 0] +var arr = List.filled(5, 0); // [0, 0, 0, 0, 0] List nums = [1, 3, 2, 5, 4]; ``` ```rust title="array.rs" /* 初始化陣列 */ let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0] -let slice: &[i32] = &[0; 5]; // 在 Rust 中,指定長度時([i32; 5])為陣列,不指定長度時(&[i32])為切片 // 由於 Rust 的陣列被設計為在編譯期確定長度,因此只能使用常數來指定長度 // Vector 是 Rust 一般情況下用作動態陣列的型別 @@ -73,13 +72,13 @@ let nums: Vec = vec![1, 3, 2, 5, 4]; ```c title="array.c" /* 初始化陣列 */ -int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 } -int nums[5] = { 1, 3, 2, 5, 4 }; +int arr[5] = {0}; // { 0, 0, 0, 0, 0 } +int nums[] = {1, 3, 2, 5, 4}; ``` ```kotlin title="array.kt" /* 初始化陣列 */ -var arr = IntArray(5) // { 0, 0, 0, 0, 0 } +val arr = IntArray(5) // { 0, 0, 0, 0, 0 } var nums = intArrayOf(1, 3, 2, 5, 4) ``` diff --git a/zh-hant/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/zh-hant/codes/snippets/chapter_array_and_linkedlist/linked_list.md index d82aada57..26b635787 100644 --- a/zh-hant/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/zh-hant/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -2,48 +2,53 @@ ```python title="" class ListNode: """鏈結串列節點類別""" + def __init__(self, val: int): - self.val: int = val # 節點值 - self.next: ListNode | None = None # 指向下一節點的引用 + self.val: int = val # 節點值 + self.next: ListNode | None = None # 指向下一節點的引用 ``` ```cpp title="" -/* 鏈結串列節點結構體 */ +/* 鏈結串列節點 */ struct ListNode { - int val; // 節點值 - ListNode *next; // 指向下一節點的指標 - ListNode(int x) : val(x), next(nullptr) {} // 建構子 + int val; // 節點值 + ListNode *next; // 後繼節點指標 + ListNode(int x) : val(x), next(nullptr) { + } }; ``` ```java title="" -/* 鏈結串列節點類別 */ -class ListNode { - int val; // 節點值 - ListNode next; // 指向下一節點的引用 - ListNode(int x) { val = x; } // 建構子 +/* 鏈結串列節點 */ +public class ListNode { + public int val; // 節點值 + public ListNode next; // 指向下一節點的引用 + + public ListNode(int x) { + val = x; + } } ``` ```csharp title="" -/* 鏈結串列節點類別 */ -class ListNode(int x) { //建構子 - public int val = x; // 節點值 - public ListNode? next; // 指向下一節點的引用 +/* 鏈結串列節點 */ +public class ListNode(int x) { + public int val = x; // 節點值 + public ListNode? next; // 指向下一節點的引用 } ``` ```go title="" -/* 鏈結串列節點結構體 */ +// ListNode 鏈結串列節點 type ListNode struct { Val int // 節點值 - Next *ListNode // 指向下一節點的指標 + Next *ListNode // 後繼節點指標 } -// NewListNode 建構子,建立一個新的鏈結串列 -func NewListNode(val int) *ListNode { +// NewListNode 鏈結串列節點建構子 +func NewListNode(v int) *ListNode { return &ListNode{ - Val: val, + Val: v, Next: nil, } } @@ -62,44 +67,54 @@ class ListNode { ``` ```javascript title="" -/* 鏈結串列節點類別 */ +/* 鏈結串列節點 */ class ListNode { + val; // 節點值 + next; // 指向下一節點的引用(指標) constructor(val, next) { - this.val = (val === undefined ? 0 : val); // 節點值 - this.next = (next === undefined ? null : next); // 指向下一節點的引用 + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```typescript title="" -/* 鏈結串列節點類別 */ +/* 鏈結串列節點 */ class ListNode { - val: number; - next: ListNode | null; + val: number; // 節點值 + next: ListNode | null; // 指向下一節點的引用 constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 節點值 - this.next = next === undefined ? null : next; // 指向下一節點的引用 + this.val = val === undefined ? 0 : val; + this.next = next === undefined ? null : next; } } ``` ```dart title="" -/* 鏈結串列節點類別 */ +/* 鏈結串列節點 */ class ListNode { int val; // 節點值 ListNode? next; // 指向下一節點的引用 + ListNode(this.val, [this.next]); // 建構子 } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; -/* 鏈結串列節點類別 */ +use std::rc::Rc; + +/* 鏈結串列節點 */ #[derive(Debug)] -struct ListNode { - val: i32, // 節點值 - next: Option>>, // 指向下一節點的指標 +pub struct ListNode { + pub val: T, // 節點值 + pub next: Option>>>, // 後繼節點指標 +} + +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None })) + } } ``` @@ -110,10 +125,10 @@ typedef struct ListNode { struct ListNode *next; // 指向下一節點的指標 } ListNode; -/* 建構子 */ +/* 建構子,初始化一個新節點 */ ListNode *newListNode(int val) { ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); + node = (ListNode *)malloc(sizeof(ListNode)); node->val = val; node->next = NULL; return node; @@ -121,16 +136,14 @@ ListNode *newListNode(int val) { ``` ```kotlin title="" -/* 鏈結串列節點類別 */ -// 建構子 -class ListNode(x: Int) { - val _val: Int = x // 節點值 - var next: ListNode? = null // 指向下一個節點的引用 +/* 鏈結串列節點 */ +class ListNode(var _val: Int) { + var next: ListNode? = null // 指向下一節點的引用 } ``` ```ruby title="" -# 鏈結串列節點類別 +### 鏈結串列節點類別 ### class ListNode attr_accessor :val # 節點值 attr_accessor :next # 指向下一節點的引用 @@ -161,11 +174,11 @@ n3.next = n4 ```cpp title="linked_list.cpp" /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ // 初始化各個節點 -ListNode* n0 = new ListNode(1); -ListNode* n1 = new ListNode(3); -ListNode* n2 = new ListNode(2); -ListNode* n3 = new ListNode(5); -ListNode* n4 = new ListNode(4); +ListNode *n0 = new ListNode(1); +ListNode *n1 = new ListNode(3); +ListNode *n2 = new ListNode(2); +ListNode *n3 = new ListNode(5); +ListNode *n4 = new ListNode(4); // 構建節點之間的引用 n0->next = n1; n1->next = n2; @@ -189,7 +202,7 @@ n3.next = n4; ``` ```csharp title="linked_list.cs" -/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 // 初始化各個節點 ListNode n0 = new(1); ListNode n1 = new(3); @@ -211,6 +224,7 @@ n1 := NewListNode(3) n2 := NewListNode(2) n3 := NewListNode(5) n4 := NewListNode(4) + // 構建節點之間的引用 n0.Next = n1 n1.Next = n2 @@ -264,7 +278,7 @@ n3.next = n4; ``` ```dart title="linked_list.dart" -/* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ +// 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 // 初始化各個節點 ListNode n0 = ListNode(1); ListNode n1 = ListNode(3); @@ -281,11 +295,11 @@ n3.next = n4; ```rust title="linked_list.rs" /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ // 初始化各個節點 -let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None })); -let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None })); -let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None })); -let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None })); -let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None })); +let n0 = ListNode::new(1); +let n1 = ListNode::new(3); +let n2 = ListNode::new(2); +let n3 = ListNode::new(5); +let n4 = ListNode::new(4); // 構建節點之間的引用 n0.borrow_mut().next = Some(n1.clone()); @@ -297,11 +311,11 @@ n3.borrow_mut().next = Some(n4.clone()); ```c title="linked_list.c" /* 初始化鏈結串列 1 -> 3 -> 2 -> 5 -> 4 */ // 初始化各個節點 -ListNode* n0 = newListNode(1); -ListNode* n1 = newListNode(3); -ListNode* n2 = newListNode(2); -ListNode* n3 = newListNode(5); -ListNode* n4 = newListNode(4); +ListNode *n0 = newListNode(1); +ListNode *n1 = newListNode(3); +ListNode *n2 = newListNode(2); +ListNode *n3 = newListNode(5); +ListNode *n4 = newListNode(4); // 構建節點之間的引用 n0->next = n1; n1->next = n2; @@ -317,11 +331,12 @@ val n1 = ListNode(3) val n2 = ListNode(2) val n3 = ListNode(5) val n4 = ListNode(4) + // 構建節點之間的引用 -n0.next = n1; -n1.next = n2; -n2.next = n3; -n3.next = n4; +n0.next = n1 +n1.next = n2 +n2.next = n3 +n3.next = n4 ``` ```ruby title="linked_list.rb" @@ -345,39 +360,46 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2 ```python title="" class ListNode: - """雙向鏈結串列節點類別""" + """雙向鏈結串列節點""" + def __init__(self, val: int): - self.val: int = val # 節點值 - self.next: ListNode | None = None # 指向後繼節點的引用 - self.prev: ListNode | None = None # 指向前驅節點的引用 + """建構子""" + self.val: int = val # 節點值 + self.next: ListNode | None = None # 後繼節點引用 + self.prev: ListNode | None = None # 前驅節點引用 ``` ```cpp title="" -/* 雙向鏈結串列節點結構體 */ -struct ListNode { - int val; // 節點值 - ListNode *next; // 指向後繼節點的指標 - ListNode *prev; // 指向前驅節點的指標 - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 建構子 +/* 雙向鏈結串列節點 */ +struct DoublyListNode { + int val; // 節點值 + DoublyListNode *next; // 後繼節點指標 + DoublyListNode *prev; // 前驅節點指標 + DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { + } }; ``` ```java title="" -/* 雙向鏈結串列節點類別 */ +/* 雙向鏈結串列節點 */ class ListNode { - int val; // 節點值 - ListNode next; // 指向後繼節點的引用 - ListNode prev; // 指向前驅節點的引用 - ListNode(int x) { val = x; } // 建構子 + int val; // 節點值 + ListNode next; // 後繼節點引用 + ListNode prev; // 前驅節點引用 + + ListNode(int val) { + this.val = val; + prev = next = null; + } } ``` ```csharp title="" -/* 雙向鏈結串列節點類別 */ -class ListNode(int x) { // 建構子 - public int val = x; // 節點值 - public ListNode? next; // 指向後繼節點的引用 - public ListNode? prev; // 指向前驅節點的引用 +/* 雙向鏈結串列節點 */ +public class ListNode(int val) { + public int val = val; // 節點值 + public ListNode? next = null; // 後繼節點引用 + public ListNode? prev = null; // 前驅節點引用 } ``` @@ -385,8 +407,8 @@ class ListNode(int x) { // 建構子 /* 雙向鏈結串列節點結構體 */ type DoublyListNode struct { Val int // 節點值 - Next *DoublyListNode // 指向後繼節點的指標 - Prev *DoublyListNode // 指向前驅節點的指標 + Next *DoublyListNode // 後繼節點指標 + Prev *DoublyListNode // 前驅節點指標 } // NewDoublyListNode 初始化 @@ -400,117 +422,119 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* 雙向鏈結串列節點類別 */ +/* 雙向鏈結串列節點 */ class ListNode { var val: Int // 節點值 - var next: ListNode? // 指向後繼節點的引用 - var prev: ListNode? // 指向前驅節點的引用 + var next: ListNode? // 後繼節點引用 + weak var prev: ListNode? // 前驅節點引用 - init(x: Int) { // 建構子 - val = x + init(val: Int) { + self.val = val } } ``` ```javascript title="" -/* 雙向鏈結串列節點類別 */ +/* 雙向鏈結串列節點 */ class ListNode { - constructor(val, next, prev) { - this.val = val === undefined ? 0 : val; // 節點值 - this.next = next === undefined ? null : next; // 指向後繼節點的引用 - this.prev = prev === undefined ? null : prev; // 指向前驅節點的引用 + prev; // 前驅節點引用(指標) + next; // 後繼節點引用(指標) + val; // 節點值 + + constructor(val) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```typescript title="" -/* 雙向鏈結串列節點類別 */ +/* 雙向鏈結串列節點 */ class ListNode { - val: number; - next: ListNode | null; - prev: ListNode | null; - constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 節點值 - this.next = next === undefined ? null : next; // 指向後繼節點的引用 - this.prev = prev === undefined ? null : prev; // 指向前驅節點的引用 + prev: ListNode | null; // 前驅節點引用(指標) + next: ListNode | null; // 後繼節點引用(指標) + val: number; // 節點值 + + constructor(val: number) { + this.val = val; + this.next = null; + this.prev = null; } } ``` ```dart title="" -/* 雙向鏈結串列節點類別 */ +/* 雙向鏈結串列節點 */ class ListNode { - int val; // 節點值 - ListNode? next; // 指向後繼節點的引用 - ListNode? prev; // 指向前驅節點的引用 - ListNode(this.val, [this.next, this.prev]); // 建構子 + int val; // 節點值 + ListNode? next; // 後繼節點引用 + ListNode? prev; // 前驅節點引用 + + ListNode(this.val, {this.next, this.prev}); } ``` ```rust title="" -use std::rc::Rc; use std::cell::RefCell; +use std::rc::Rc; -/* 雙向鏈結串列節點型別 */ -#[derive(Debug)] -struct ListNode { - val: i32, // 節點值 - next: Option>>, // 指向後繼節點的指標 - prev: Option>>, // 指向前驅節點的指標 +/* 雙向鏈結串列節點 */ +pub struct ListNode { + pub val: T, // 節點值 + pub next: Option>>>, // 後繼節點指標 + pub prev: Option>>>, // 前驅節點指標 } -/* 建構子 */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { +impl ListNode { + pub fn new(val: T) -> Rc>> { + Rc::new(RefCell::new(ListNode { val, next: None, prev: None, - } + })) } } ``` ```c title="" -/* 雙向鏈結串列節點結構體 */ -typedef struct ListNode { - int val; // 節點值 - struct ListNode *next; // 指向後繼節點的指標 - struct ListNode *prev; // 指向前驅節點的指標 -} ListNode; +/* 雙向鏈結串列節點 */ +typedef struct DoublyListNode { + int val; // 節點值 + struct DoublyListNode *next; // 後繼節點指標 + struct DoublyListNode *prev; // 前驅節點指標 +} DoublyListNode; /* 建構子 */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; +DoublyListNode *newDoublyListNode(int num) { + DoublyListNode *new = (DoublyListNode *)malloc(sizeof(DoublyListNode)); + new->val = num; + new->next = NULL; + new->prev = NULL; + return new; } ``` ```kotlin title="" -/* 雙向鏈結串列節點類別 */ -// 建構子 -class ListNode(x: Int) { - val _val: Int = x // 節點值 - var next: ListNode? = null // 指向後繼節點的引用 - var prev: ListNode? = null // 指向前驅節點的引用 +/* 雙向鏈結串列節點 */ +class ListNode( + var _val: Int // 節點值 +) { + var next: ListNode? = null // 後繼節點引用 + var prev: ListNode? = null // 前驅節點引用 } ``` ```ruby title="" -# 雙向鏈結串列節點類別 +### 雙向鏈結串列節點 ### class ListNode - attr_accessor :val # 節點值 - attr_accessor :next # 指向後繼節點的引用 - attr_accessor :prev # 指向前驅節點的引用 + attr_accessor :val # 節點值 + attr_accessor :next # 後繼節點引用 + attr_accessor :prev # 前驅節點引用 - def initialize(val=0, next_node=nil, prev_node=nil) + ### 建構子 ### + def initialize(val) @val = val - @next = next_node - @prev = prev_node end end ``` diff --git a/zh-hant/codes/snippets/chapter_array_and_linkedlist/list.md b/zh-hant/codes/snippets/chapter_array_and_linkedlist/list.md index 4335b5b0c..b224419ce 100644 --- a/zh-hant/codes/snippets/chapter_array_and_linkedlist/list.md +++ b/zh-hant/codes/snippets/chapter_array_and_linkedlist/list.md @@ -2,25 +2,24 @@ ```python title="list.py" # 初始化串列 # 無初始值 -nums1: list[int] = [] +empty_nums: list[int] = [] # 有初始值 nums: list[int] = [1, 3, 2, 5, 4] ``` ```cpp title="list.cpp" /* 初始化串列 */ -// 需注意,C++ 中 vector 即是本文描述的 nums // 無初始值 -vector nums1; +vector emptyNums; // 有初始值 -vector nums = { 1, 3, 2, 5, 4 }; +vector nums = {1, 3, 2, 5, 4}; ``` ```java title="list.java" /* 初始化串列 */ // 無初始值 -List nums1 = new ArrayList<>(); -// 有初始值(注意陣列的元素型別需為 int[] 的包裝類別 Integer[]) +List emptyNums = new ArrayList<>(); +// 有初始值(注意陣列型別需為 Integer[] 而非 int[],因為串列元素只能是 int 的包裝類別 Integer) Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 }; List nums = new ArrayList<>(Arrays.asList(numbers)); ``` @@ -28,7 +27,7 @@ List nums = new ArrayList<>(Arrays.asList(numbers)); ```csharp title="list.cs" /* 初始化串列 */ // 無初始值 -List nums1 = []; +List emptyNums = []; // 有初始值 int[] numbers = [1, 3, 2, 5, 4]; List nums = [.. numbers]; @@ -37,7 +36,7 @@ List nums = [.. numbers]; ```go title="list_test.go" /* 初始化串列 */ // 無初始值 -nums1 := []int{} +emptyNums := []int{} // 有初始值 nums := []int{1, 3, 2, 5, 4} ``` @@ -45,7 +44,7 @@ nums := []int{1, 3, 2, 5, 4} ```swift title="list.swift" /* 初始化串列 */ // 無初始值 -let nums1: [Int] = [] +let emptyNums: [Int] = [] // 有初始值 var nums = [1, 3, 2, 5, 4] ``` @@ -53,7 +52,7 @@ var nums = [1, 3, 2, 5, 4] ```javascript title="list.js" /* 初始化串列 */ // 無初始值 -const nums1 = []; +const emptyNums = []; // 有初始值 const nums = [1, 3, 2, 5, 4]; ``` @@ -61,7 +60,7 @@ const nums = [1, 3, 2, 5, 4]; ```typescript title="list.ts" /* 初始化串列 */ // 無初始值 -const nums1: number[] = []; +const emptyNums: number[] = []; // 有初始值 const nums: number[] = [1, 3, 2, 5, 4]; ``` @@ -69,15 +68,15 @@ const nums: number[] = [1, 3, 2, 5, 4]; ```dart title="list.dart" /* 初始化串列 */ // 無初始值 -List nums1 = []; +List emptyNums = []; // 有初始值 List nums = [1, 3, 2, 5, 4]; ``` ```rust title="list.rs" -/* 初始化串列 */ +// 初始化串列 // 無初始值 -let nums1: Vec = Vec::new(); +let empty_nums: Vec = Vec::new(); // 有初始值 let mut nums: Vec = vec![1, 3, 2, 5, 4]; ``` @@ -89,62 +88,61 @@ let mut nums: Vec = vec![1, 3, 2, 5, 4]; ```kotlin title="list.kt" /* 初始化串列 */ // 無初始值 -var nums1 = listOf() +val emptyNums = mutableListOf() // 有初始值 -var numbers = arrayOf(1, 3, 2, 5, 4) -var nums = numbers.toMutableList() +val nums = mutableListOf(1, 3, 2, 5, 4) ``` ```ruby title="list.rb" # 初始化串列 # 無初始值 -nums1 = [] +empty_nums = [] # 有初始值 nums = [1, 3, 2, 5, 4] ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20%23%20%E7%84%A1%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20%23%20%E7%84%A1%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20empty_nums%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" # 訪問元素 -num: int = nums[1] # 訪問索引 1 處的元素 +x: int = nums[1] # 訪問索引 1 處的元素 # 更新元素 -nums[1] = 0 # 將索引 1 處的元素更新為 0 +nums[1] = 0 # 將索引 1 處的元素更新為 0 ``` ```cpp title="list.cpp" /* 訪問元素 */ -int num = nums[1]; // 訪問索引 1 處的元素 +int num = nums[1]; // 訪問索引 1 處的元素 /* 更新元素 */ -nums[1] = 0; // 將索引 1 處的元素更新為 0 +nums[1] = 0; // 將索引 1 處的元素更新為 0 ``` ```java title="list.java" /* 訪問元素 */ -int num = nums.get(1); // 訪問索引 1 處的元素 +int num = nums.get(1); // 訪問索引 1 處的元素 /* 更新元素 */ -nums.set(1, 0); // 將索引 1 處的元素更新為 0 +nums.set(1, 0); // 將索引 1 處的元素更新為 0 ``` ```csharp title="list.cs" /* 訪問元素 */ -int num = nums[1]; // 訪問索引 1 處的元素 +int num = nums[1]; // 訪問索引 1 處的元素 /* 更新元素 */ -nums[1] = 0; // 將索引 1 處的元素更新為 0 +nums[1] = 0; // 將索引 1 處的元素更新為 0 ``` ```go title="list_test.go" /* 訪問元素 */ -num := nums[1] // 訪問索引 1 處的元素 +num := nums[1] // 訪問索引 1 處的元素 /* 更新元素 */ -nums[1] = 0 // 將索引 1 處的元素更新為 0 +nums[1] = 0 // 將索引 1 處的元素更新為 0 ``` ```swift title="list.swift" @@ -157,33 +155,34 @@ nums[1] = 0 // 將索引 1 處的元素更新為 0 ```javascript title="list.js" /* 訪問元素 */ -const num = nums[1]; // 訪問索引 1 處的元素 +const num = nums[1]; // 訪問索引 1 處的元素 /* 更新元素 */ -nums[1] = 0; // 將索引 1 處的元素更新為 0 +nums[1] = 0; // 將索引 1 處的元素更新為 0 ``` ```typescript title="list.ts" /* 訪問元素 */ -const num: number = nums[1]; // 訪問索引 1 處的元素 +const num: number = nums[1]; // 訪問索引 1 處的元素 /* 更新元素 */ -nums[1] = 0; // 將索引 1 處的元素更新為 0 +nums[1] = 0; // 將索引 1 處的元素更新為 0 ``` ```dart title="list.dart" /* 訪問元素 */ -int num = nums[1]; // 訪問索引 1 處的元素 +int _num = nums[1]; // 訪問索引 1 處的元素 /* 更新元素 */ -nums[1] = 0; // 將索引 1 處的元素更新為 0 +nums[1] = 0; // 將索引 1 處的元素更新為 0 ``` ```rust title="list.rs" -/* 訪問元素 */ -let num: i32 = nums[1]; // 訪問索引 1 處的元素 -/* 更新元素 */ -nums[1] = 0; // 將索引 1 處的元素更新為 0 +// 訪問元素 +let num = nums[1]; // 訪問索引 1 處的元素 + +// 更新元素 +nums[1] = 0; // 將索引 1 處的元素更新為 0 ``` ```c title="list.c" @@ -192,20 +191,22 @@ nums[1] = 0; // 將索引 1 處的元素更新為 0 ```kotlin title="list.kt" /* 訪問元素 */ -val num = nums[1] // 訪問索引 1 處的元素 +val num = nums[1] // 訪問索引 1 處的元素 + /* 更新元素 */ -nums[1] = 0 // 將索引 1 處的元素更新為 0 +nums[1] = 0 // 將索引 1 處的元素更新為 0 ``` ```ruby title="list.rb" # 訪問元素 num = nums[1] # 訪問索引 1 處的元素 + # 更新元素 nums[1] = 0 # 將索引 1 處的元素更新為 0 ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E5%85%83%E7%B4%A0%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E8%A8%AA%E5%95%8F%E7%B4%A2%E5%BC%95%201%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%87%E7%B4%A2%E5%BC%95%201%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E7%82%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%B8%B2%E5%88%97%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20%E8%A8%AA%E5%95%8F%E5%85%83%E7%B4%A0%0A%20%20%20%20x%20%3D%20nums%5B1%5D%20%20%23%20%E8%A8%AA%E5%95%8F%E7%B4%A2%E5%BC%95%201%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%87%E7%B4%A2%E5%BC%95%201%20%E8%99%95%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E7%82%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false ```python title="list.py" @@ -223,7 +224,7 @@ nums.append(4) nums.insert(3, 6) # 在索引 3 處插入數字 6 # 刪除元素 -nums.pop(3) # 刪除索引 3 處的元素 +nums.pop(3) # 刪除索引 3 處的元素 ``` ```cpp title="list.cpp" @@ -238,10 +239,10 @@ nums.push_back(5); nums.push_back(4); /* 在中間插入元素 */ -nums.insert(nums.begin() + 3, 6); // 在索引 3 處插入數字 6 +nums.insert(nums.begin() + 3, 6); // 在索引 3 處插入數字 6 /* 刪除元素 */ -nums.erase(nums.begin() + 3); // 刪除索引 3 處的元素 +nums.erase(nums.begin() + 3); // 刪除索引 3 處的元素 ``` ```java title="list.java" @@ -256,10 +257,10 @@ nums.add(5); nums.add(4); /* 在中間插入元素 */ -nums.add(3, 6); // 在索引 3 處插入數字 6 +nums.add(3, 6); // 在索引 3 處插入數字 6 /* 刪除元素 */ -nums.remove(3); // 刪除索引 3 處的元素 +nums.remove(3); // 刪除索引 3 處的元素 ``` ```csharp title="list.cs" @@ -274,10 +275,10 @@ nums.Add(5); nums.Add(4); /* 在中間插入元素 */ -nums.Insert(3, 6); // 在索引 3 處插入數字 6 +nums.Insert(3, 6); // 在索引 3 處插入數字 6 /* 刪除元素 */ -nums.RemoveAt(3); // 刪除索引 3 處的元素 +nums.RemoveAt(3); // 刪除索引 3 處的元素 ``` ```go title="list_test.go" @@ -331,7 +332,7 @@ nums.push(4); nums.splice(3, 0, 6); // 在索引 3 處插入數字 6 /* 刪除元素 */ -nums.splice(3, 1); // 刪除索引 3 處的元素 +nums.splice(3, 1); // 刪除索引 3 處的元素 ``` ```typescript title="list.ts" @@ -349,7 +350,7 @@ nums.push(4); nums.splice(3, 0, 6); // 在索引 3 處插入數字 6 /* 刪除元素 */ -nums.splice(3, 1); // 刪除索引 3 處的元素 +nums.splice(3, 1); // 刪除索引 3 處的元素 ``` ```dart title="list.dart" @@ -371,21 +372,21 @@ nums.removeAt(3); // 刪除索引 3 處的元素 ``` ```rust title="list.rs" -/* 清空串列 */ +// 清空串列 nums.clear(); -/* 在尾部新增元素 */ +// 在尾部新增元素 nums.push(1); nums.push(3); nums.push(2); nums.push(5); nums.push(4); -/* 在中間插入元素 */ -nums.insert(3, 6); // 在索引 3 處插入數字 6 +// 在中間插入元素 +nums.insert(3, 6); // 在索引 3 處插入數字 6 -/* 刪除元素 */ -nums.remove(3); // 刪除索引 3 處的元素 +// 刪除元素 +nums.remove(3); // 刪除索引 3 處的元素 ``` ```c title="list.c" @@ -394,20 +395,20 @@ nums.remove(3); // 刪除索引 3 處的元素 ```kotlin title="list.kt" /* 清空串列 */ -nums.clear(); +nums.clear() /* 在尾部新增元素 */ -nums.add(1); -nums.add(3); -nums.add(2); -nums.add(5); -nums.add(4); +nums.add(1) +nums.add(3) +nums.add(2) +nums.add(5) +nums.add(4) /* 在中間插入元素 */ -nums.add(3, 6); // 在索引 3 處插入數字 6 +nums.add(3, 6) // 在索引 3 處插入數字 6 /* 刪除元素 */ -nums.removeAt(3); // 刪除索引 3 處的元素 +nums.removeAt(3) // 刪除索引 3 處的元素 ``` ```ruby title="list.rb" @@ -452,8 +453,8 @@ for (int i = 0; i < nums.size(); i++) { /* 直接走訪串列元素 */ count = 0; -for (int num : nums) { - count += num; +for (int x : nums) { + count += x; } ``` @@ -465,8 +466,8 @@ for (int i = 0; i < nums.size(); i++) { } /* 直接走訪串列元素 */ -for (int num : nums) { - count += num; +for (int x : nums) { + count += x; } ``` @@ -479,8 +480,8 @@ for (int i = 0; i < nums.Count; i++) { /* 直接走訪串列元素 */ count = 0; -foreach (int num in nums) { - count += num; +foreach (int x in nums) { + count += x; } ``` @@ -493,8 +494,8 @@ for i := 0; i < len(nums); i++ { /* 直接走訪串列元素 */ count = 0 -for _, num := range nums { - count += num +for _, x := range nums { + count += x } ``` @@ -507,8 +508,8 @@ for i in nums.indices { /* 直接走訪串列元素 */ count = 0 -for num in nums { - count += num +for x in nums { + count += x } ``` @@ -521,8 +522,8 @@ for (let i = 0; i < nums.length; i++) { /* 直接走訪串列元素 */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` @@ -535,8 +536,8 @@ for (let i = 0; i < nums.length; i++) { /* 直接走訪串列元素 */ count = 0; -for (const num of nums) { - count += num; +for (const x of nums) { + count += x; } ``` @@ -544,13 +545,13 @@ for (const num of nums) { /* 透過索引走訪串列 */ int count = 0; for (var i = 0; i < nums.length; i++) { - count += nums[i]; + count += nums[i]; } /* 直接走訪串列元素 */ count = 0; -for (var num in nums) { - count += num; +for (var x in nums) { + count += x; } ``` @@ -563,8 +564,8 @@ for i in 0..nums.len() { // 直接走訪串列元素 _count = 0; -for num in &nums { - _count += num; +for x in &nums { + _count += x; } ``` @@ -580,8 +581,8 @@ for (i in nums.indices) { } /* 直接走訪串列元素 */ -for (num in nums) { - count += num +for (j in nums) { + count += j } ``` @@ -589,13 +590,13 @@ for (num in nums) { # 透過索引走訪串列 count = 0 for i in 0...nums.length - count += nums[i] + count += nums[i] end # 直接走訪串列元素 count = 0 -for num in nums - count += num +nums.each do |x| + count += x end ``` @@ -605,13 +606,13 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 ```python title="list.py" # 拼接兩個串列 -nums1: list[int] = [6, 8, 7, 10, 9] +nums1 = [6, 8, 7, 10, 9] nums += nums1 # 將串列 nums1 拼接到 nums 之後 ``` ```cpp title="list.cpp" /* 拼接兩個串列 */ -vector nums1 = { 6, 8, 7, 10, 9 }; +vector nums1 = {6, 8, 7, 10, 9}; // 將串列 nums1 拼接到 nums 之後 nums.insert(nums.end(), nums1.begin(), nums1.end()); ``` @@ -619,19 +620,19 @@ nums.insert(nums.end(), nums1.begin(), nums1.end()); ```java title="list.java" /* 拼接兩個串列 */ List nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 })); -nums.addAll(nums1); // 將串列 nums1 拼接到 nums 之後 +nums.addAll(nums1); // 將串列 nums1 拼接到 nums 之後 ``` ```csharp title="list.cs" /* 拼接兩個串列 */ List nums1 = [6, 8, 7, 10, 9]; -nums.AddRange(nums1); // 將串列 nums1 拼接到 nums 之後 +nums.AddRange(nums1); // 將串列 nums1 拼接到 nums 之後 ``` ```go title="list_test.go" /* 拼接兩個串列 */ nums1 := []int{6, 8, 7, 10, 9} -nums = append(nums, nums1...) // 將串列 nums1 拼接到 nums 之後 +nums = append(nums, nums1...) // 將串列 nums1 拼接到 nums 之後 ``` ```swift title="list.swift" @@ -643,25 +644,25 @@ nums.append(contentsOf: nums1) // 將串列 nums1 拼接到 nums 之後 ```javascript title="list.js" /* 拼接兩個串列 */ const nums1 = [6, 8, 7, 10, 9]; -nums.push(...nums1); // 將串列 nums1 拼接到 nums 之後 +nums.push(...nums1); // 將串列 nums1 拼接到 nums 之後 ``` ```typescript title="list.ts" /* 拼接兩個串列 */ const nums1: number[] = [6, 8, 7, 10, 9]; -nums.push(...nums1); // 將串列 nums1 拼接到 nums 之後 +nums.push(...nums1); // 將串列 nums1 拼接到 nums 之後 ``` ```dart title="list.dart" /* 拼接兩個串列 */ List nums1 = [6, 8, 7, 10, 9]; -nums.addAll(nums1); // 將串列 nums1 拼接到 nums 之後 +nums.addAll(nums1); // 將串列 nums1 拼接到 nums 之後 ``` ```rust title="list.rs" -/* 拼接兩個串列 */ -let nums1: Vec = vec![6, 8, 7, 10, 9]; -nums.extend(nums1); +// 拼接兩個串列 +let mut nums1 = vec![6, 8, 7, 10, 9]; +nums.append(&mut nums1); // append 會移走 nums1 的元素,之後 nums1 為空 ``` ```c title="list.c" @@ -670,8 +671,8 @@ nums.extend(nums1); ```kotlin title="list.kt" /* 拼接兩個串列 */ -val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList() -nums.addAll(nums1) // 將串列 nums1 拼接到 nums 之後 +val nums1 = mutableListOf(6, 8, 7, 10, 9) +nums.addAll(nums1) // 將串列 nums1 拼接到 nums 之後 ``` ```ruby title="list.rb" @@ -691,12 +692,12 @@ nums.sort() # 排序後,串列元素從小到大排列 ```cpp title="list.cpp" /* 排序串列 */ -sort(nums.begin(), nums.end()); // 排序後,串列元素從小到大排列 +sort(nums.begin(), nums.end()); // 排序後,串列元素從小到大排列 ``` ```java title="list.java" /* 排序串列 */ -Collections.sort(nums); // 排序後,串列元素從小到大排列 +Collections.sort(nums); // 排序後,串列元素從小到大排列 ``` ```csharp title="list.cs" @@ -706,7 +707,7 @@ nums.Sort(); // 排序後,串列元素從小到大排列 ```go title="list_test.go" /* 排序串列 */ -sort.Ints(nums) // 排序後,串列元素從小到大排列 +sort.Ints(nums) // 排序後,串列元素從小到大排列 ``` ```swift title="list.swift" @@ -716,12 +717,12 @@ nums.sort() // 排序後,串列元素從小到大排列 ```javascript title="list.js" /* 排序串列 */ -nums.sort((a, b) => a - b); // 排序後,串列元素從小到大排列 +nums.sort((a, b) => a - b); // 排序後,串列元素從小到大排列 ``` ```typescript title="list.ts" /* 排序串列 */ -nums.sort((a, b) => a - b); // 排序後,串列元素從小到大排列 +nums.sort((a, b) => a - b); // 排序後,串列元素從小到大排列 ``` ```dart title="list.dart" @@ -730,7 +731,7 @@ nums.sort(); // 排序後,串列元素從小到大排列 ``` ```rust title="list.rs" -/* 排序串列 */ +// 排序串列 nums.sort(); // 排序後,串列元素從小到大排列 ``` diff --git a/zh-hant/codes/snippets/chapter_hashing/hash_algorithm.md b/zh-hant/codes/snippets/chapter_hashing/hash_algorithm.md index 8b47cfa93..2405ed69f 100644 --- a/zh-hant/codes/snippets/chapter_hashing/hash_algorithm.md +++ b/zh-hant/codes/snippets/chapter_hashing/hash_algorithm.md @@ -2,44 +2,54 @@ ```python title="built_in_hash.py" num = 3 hash_num = hash(num) +print(f"整數 {num} 的雜湊值為 {hash_num}") # 整數 3 的雜湊值為 3 bol = True hash_bol = hash(bol) +print(f"布林量 {bol} 的雜湊值為 {hash_bol}") # 布林量 True 的雜湊值為 1 dec = 3.14159 hash_dec = hash(dec) +print(f"小數 {dec} 的雜湊值為 {hash_dec}") # 小數 3.14159 的雜湊值為 326484311674566659 str = "Hello 演算法" hash_str = hash(str) +print(f"字串“{str}”的雜湊值為 {hash_str}") # 字串“Hello 演算法”的雜湊值為 4617003410720528961 tup = (12836, "小哈") hash_tup = hash(tup) +print(f"元組 {tup} 的雜湊值為 {hash_tup}") # 元組 (12836, '小哈') 的雜湊值為 1029005403108185979 obj = ListNode(0) hash_obj = hash(obj) -# 節點物件 的雜湊值為 274267521 +print(f"節點物件 {obj} 的雜湊值為 {hash_obj}") +# 節點物件 的雜湊值為 274267521 ``` ```cpp title="built_in_hash.cpp" int num = 3; size_t hashNum = hash()(num); +cout << "整數 " << num << " 的雜湊值為 " << hashNum << "\n"; // 整數 3 的雜湊值為 3 bool bol = true; size_t hashBol = hash()(bol); +cout << "布林量 " << bol << " 的雜湊值為 " << hashBol << "\n"; // 布林量 1 的雜湊值為 1 double dec = 3.14159; size_t hashDec = hash()(dec); +cout << "小數 " << dec << " 的雜湊值為 " << hashDec << "\n"; // 小數 3.14159 的雜湊值為 4614256650576692846 string str = "Hello 演算法"; size_t hashStr = hash()(str); +cout << "字串“" << str << "”的雜湊值為 " << hashStr << "\n"; // 字串“Hello 演算法”的雜湊值為 15466937326284535026 // 在 C++ 中,內建 std::hash() 僅提供基本資料型別的雜湊值計算 @@ -49,53 +59,65 @@ size_t hashStr = hash()(str); ```java title="built_in_hash.java" int num = 3; int hashNum = Integer.hashCode(num); +System.out.println("整數 " + num + " 的雜湊值為 " + hashNum); // 整數 3 的雜湊值為 3 boolean bol = true; int hashBol = Boolean.hashCode(bol); +System.out.println("布林量 " + bol + " 的雜湊值為 " + hashBol); // 布林量 true 的雜湊值為 1231 double dec = 3.14159; int hashDec = Double.hashCode(dec); +System.out.println("小數 " + dec + " 的雜湊值為 " + hashDec); // 小數 3.14159 的雜湊值為 -1340954729 String str = "Hello 演算法"; int hashStr = str.hashCode(); +System.out.println("字串“" + str + "”的雜湊值為 " + hashStr); // 字串“Hello 演算法”的雜湊值為 -727081396 Object[] arr = { 12836, "小哈" }; -int hashTup = Arrays.hashCode(arr); +int hashArr = Arrays.hashCode(arr); +System.out.println("陣列 " + Arrays.toString(arr) + " 的雜湊值為 " + hashArr); // 陣列 [12836, 小哈] 的雜湊值為 1151158 ListNode obj = new ListNode(0); int hashObj = obj.hashCode(); +System.out.println("節點物件 " + obj + " 的雜湊值為 " + hashObj); // 節點物件 utils.ListNode@7dc5e7b4 的雜湊值為 2110121908 ``` ```csharp title="built_in_hash.cs" int num = 3; int hashNum = num.GetHashCode(); -// 整數 3 的雜湊值為 3; +Console.WriteLine("整數 " + num + " 的雜湊值為 " + hashNum); +// 整數 3 的雜湊值為 3 bool bol = true; int hashBol = bol.GetHashCode(); -// 布林量 true 的雜湊值為 1; +Console.WriteLine("布林量 " + bol + " 的雜湊值為 " + hashBol); +// 布林量 True 的雜湊值為 1 double dec = 3.14159; int hashDec = dec.GetHashCode(); -// 小數 3.14159 的雜湊值為 -1340954729; +Console.WriteLine("小數 " + dec + " 的雜湊值為 " + hashDec); +// 小數 3.14159 的雜湊值為 -1340954729 string str = "Hello 演算法"; int hashStr = str.GetHashCode(); -// 字串“Hello 演算法”的雜湊值為 -586107568; +Console.WriteLine("字串“" + str + "”的雜湊值為 " + hashStr); +// 字串“Hello 演算法”的雜湊值為 -586107568 object[] arr = [12836, "小哈"]; -int hashTup = arr.GetHashCode(); -// 陣列 [12836, 小哈] 的雜湊值為 42931033; +int hashArr = arr.GetHashCode(); +Console.WriteLine("陣列 [" + string.Join(", ", arr) + "] 的雜湊值為 " + hashArr); +// 陣列 [12836, 小哈] 的雜湊值為 42931033 ListNode obj = new(0); int hashObj = obj.GetHashCode(); -// 節點物件 0 的雜湊值為 39053774; +Console.WriteLine("節點物件 " + obj + " 的雜湊值為 " + hashObj); +// 節點物件 0 的雜湊值為 39053774 ``` ```go title="built_in_hash.go" @@ -105,26 +127,32 @@ int hashObj = obj.GetHashCode(); ```swift title="built_in_hash.swift" let num = 3 let hashNum = num.hashValue +print("整數 \(num) 的雜湊值為 \(hashNum)") // 整數 3 的雜湊值為 9047044699613009734 let bol = true let hashBol = bol.hashValue +print("布林量 \(bol) 的雜湊值為 \(hashBol)") // 布林量 true 的雜湊值為 -4431640247352757451 let dec = 3.14159 let hashDec = dec.hashValue +print("小數 \(dec) 的雜湊值為 \(hashDec)") // 小數 3.14159 的雜湊值為 -2465384235396674631 let str = "Hello 演算法" let hashStr = str.hashValue +print("字串“\(str)”的雜湊值為 \(hashStr)") // 字串“Hello 演算法”的雜湊值為 -7850626797806988787 let arr = [AnyHashable(12836), AnyHashable("小哈")] -let hashTup = arr.hashValue +let hashArr = arr.hashValue +print("陣列 \(arr) 的雜湊值為 \(hashArr)") // 陣列 [AnyHashable(12836), AnyHashable("小哈")] 的雜湊值為 -2308633508154532996 let obj = ListNode(x: 0) let hashObj = obj.hashValue +print("節點物件 \(obj) 的雜湊值為 \(hashObj)") // 節點物件 utils.ListNode 的雜湊值為 -2434780518035996159 ``` @@ -139,26 +167,32 @@ let hashObj = obj.hashValue ```dart title="built_in_hash.dart" int num = 3; int hashNum = num.hashCode; +print("整數 $num 的雜湊值為 $hashNum"); // 整數 3 的雜湊值為 34803 bool bol = true; int hashBol = bol.hashCode; -// 布林值 true 的雜湊值為 1231 +print("布林量 $bol 的雜湊值為 $hashBol"); +// 布林量 true 的雜湊值為 1231 double dec = 3.14159; int hashDec = dec.hashCode; +print("小數 $dec 的雜湊值為 $hashDec"); // 小數 3.14159 的雜湊值為 2570631074981783 String str = "Hello 演算法"; int hashStr = str.hashCode; +print("字串“$str”的雜湊值為 $hashStr"); // 字串“Hello 演算法”的雜湊值為 468167534 List arr = [12836, "小哈"]; int hashArr = arr.hashCode; +print("陣列 $arr 的雜湊值為 $hashArr"); // 陣列 [12836, 小哈] 的雜湊值為 976512528 -ListNode obj = new ListNode(0); +ListNode obj = ListNode(0); int hashObj = obj.hashCode; +print("節點物件 $obj 的雜湊值為 $hashObj"); // 節點物件 Instance of 'ListNode' 的雜湊值為 1033450432 ``` @@ -170,37 +204,43 @@ let num = 3; let mut num_hasher = DefaultHasher::new(); num.hash(&mut num_hasher); let hash_num = num_hasher.finish(); +println!("整數 {} 的雜湊值為 {}", num, hash_num); // 整數 3 的雜湊值為 568126464209439262 let bol = true; let mut bol_hasher = DefaultHasher::new(); bol.hash(&mut bol_hasher); let hash_bol = bol_hasher.finish(); +println!("布林量 {} 的雜湊值為 {}", bol, hash_bol); // 布林量 true 的雜湊值為 4952851536318644461 let dec: f32 = 3.14159; let mut dec_hasher = DefaultHasher::new(); dec.to_bits().hash(&mut dec_hasher); let hash_dec = dec_hasher.finish(); +println!("小數 {} 的雜湊值為 {}", dec, hash_dec); // 小數 3.14159 的雜湊值為 2566941990314602357 let str = "Hello 演算法"; let mut str_hasher = DefaultHasher::new(); str.hash(&mut str_hasher); let hash_str = str_hasher.finish(); +println!("字串“{}”的雜湊值為 {}", str, hash_str); // 字串“Hello 演算法”的雜湊值為 16092673739211250988 -let arr = (&12836, &"小哈"); +let tup = (&12836, &"小哈"); let mut tup_hasher = DefaultHasher::new(); -arr.hash(&mut tup_hasher); +tup.hash(&mut tup_hasher); let hash_tup = tup_hasher.finish(); +println!("元組 {:?} 的雜湊值為 {}", tup, hash_tup); // 元組 (12836, "小哈") 的雜湊值為 1885128010422702749 let node = ListNode::new(42); -let mut hasher = DefaultHasher::new(); -node.borrow().val.hash(&mut hasher); -let hash = hasher.finish(); -// 節點物件 RefCell { value: ListNode { val: 42, next: None } } 的雜湊值為15387811073369036852 +let mut node_hasher = DefaultHasher::new(); +node.borrow().val.hash(&mut node_hasher); +let hash_node = node_hasher.finish(); +println!("節點物件 {:?} 的雜湊值為 {}", node, hash_node); +// 節點物件 RefCell { value: ListNode { val: 42, next: None } } 的雜湊值為 15387811073369036852 ``` ```c title="built_in_hash.c" @@ -210,54 +250,66 @@ let hash = hasher.finish(); ```kotlin title="built_in_hash.kt" val num = 3 val hashNum = num.hashCode() +println("整數 $num 的雜湊值為 $hashNum") // 整數 3 的雜湊值為 3 val bol = true val hashBol = bol.hashCode() +println("布林量 $bol 的雜湊值為 $hashBol") // 布林量 true 的雜湊值為 1231 val dec = 3.14159 val hashDec = dec.hashCode() +println("小數 $dec 的雜湊值為 $hashDec") // 小數 3.14159 的雜湊值為 -1340954729 val str = "Hello 演算法" val hashStr = str.hashCode() +println("字串“$str”的雜湊值為 $hashStr") // 字串“Hello 演算法”的雜湊值為 -727081396 val arr = arrayOf(12836, "小哈") -val hashTup = arr.hashCode() -// 陣列 [12836, 小哈] 的雜湊值為 189568618 +val hashArr = arr.contentHashCode() +println("陣列 ${arr.contentToString()} 的雜湊值為 $hashArr") +// 陣列 [12836, 小哈] 的雜湊值為 1151158 val obj = ListNode(0) val hashObj = obj.hashCode() +println("節點物件 $obj 的雜湊值為 $hashObj") // 節點物件 utils.ListNode@1d81eb93 的雜湊值為 495053715 ``` ```ruby title="built_in_hash.rb" num = 3 hash_num = num.hash +puts "整數 #{num} 的雜湊值為 #{hash_num}" # 整數 3 的雜湊值為 -4385856518450339636 bol = true hash_bol = bol.hash +puts "布林量 #{bol} 的雜湊值為 #{hash_bol}" # 布林量 true 的雜湊值為 -1617938112149317027 dec = 3.14159 hash_dec = dec.hash +puts "小數 #{dec} 的雜湊值為 #{hash_dec}" # 小數 3.14159 的雜湊值為 -1479186995943067893 str = "Hello 演算法" hash_str = str.hash +puts "字串“#{str}”的雜湊值為 #{hash_str}" # 字串“Hello 演算法”的雜湊值為 -4075943250025831763 -tup = [12836, '小哈'] -hash_tup = tup.hash -# 元組 (12836, '小哈') 的雜湊值為 1999544809202288822 +arr = [12836, '小哈'] +hash_arr = arr.hash +puts "陣列 #{arr} 的雜湊值為 #{hash_arr}" +# 陣列 [12836, "小哈"] 的雜湊值為 1999544809202288822 obj = ListNode.new(0) hash_obj = obj.hash +puts "節點物件 #{obj} 的雜湊值為 #{hash_obj}" # 節點物件 # 的雜湊值為 4302940560806366381 ``` -https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%BE%8C%E7%B9%BC%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B8%203%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%E5%B8%83%E6%9E%97%E9%87%8F%20True%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B8%203.14159%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E6%BC%94%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%E5%AD%97%E4%B8%B2%E2%80%9CHello%20%E6%BC%94%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%E5%85%83%E7%B5%84%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E7%89%A9%E4%BB%B6%20%3CListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%8F%88%E7%B5%90%E4%B8%B2%E5%88%97%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%BE%8C%E7%B9%BC%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20print%28f%22%E6%95%B4%E6%95%B8%20%7Bnum%7D%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20%7Bhash_num%7D%22%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B8%203%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20print%28f%22%E5%B8%83%E6%9E%97%E9%87%8F%20%7Bbol%7D%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20%7Bhash_bol%7D%22%29%0A%20%20%20%20%23%20%E5%B8%83%E6%9E%97%E9%87%8F%20True%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20print%28f%22%E5%B0%8F%E6%95%B8%20%7Bdec%7D%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20%7Bhash_dec%7D%22%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B8%203.14159%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E6%BC%94%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20print%28f%22%E5%AD%97%E4%B8%B2%E2%80%9C%7Bstr%7D%E2%80%9D%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20%7Bhash_str%7D%22%29%0A%20%20%20%20%23%20%E5%AD%97%E4%B8%B2%E2%80%9CHello%20%E6%BC%94%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20print%28f%22%E5%85%83%E7%B5%84%20%7Btup%7D%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20%7Bhash_tup%7D%22%29%0A%20%20%20%20%23%20%E5%85%83%E7%B5%84%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20print%28f%22%E7%AF%80%E9%BB%9E%E7%89%A9%E4%BB%B6%20%7Bobj%7D%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20%7Bhash_obj%7D%22%29%0A%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E7%89%A9%E4%BB%B6%20%3Cmodules.list_node.ListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E9%9B%9C%E6%B9%8A%E5%80%BC%E7%82%BA%20274267521%0A&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_hashing/hash_map.md b/zh-hant/codes/snippets/chapter_hashing/hash_map.md index 205410178..b0a477d83 100644 --- a/zh-hant/codes/snippets/chapter_hashing/hash_map.md +++ b/zh-hant/codes/snippets/chapter_hashing/hash_map.md @@ -1,7 +1,7 @@ ```python title="hash_map.py" # 初始化雜湊表 -hmap: dict = {} +hmap = dict[int, str]() # 新增操作 # 在雜湊表中新增鍵值對 (key, value) @@ -128,6 +128,7 @@ map.removeValue(forKey: 10583) ```javascript title="hash_map.js" /* 初始化雜湊表 */ const map = new Map(); + /* 新增操作 */ // 在雜湊表中新增鍵值對 (key, value) map.set(12836, '小哈'); @@ -148,6 +149,7 @@ map.delete(10583); ```typescript title="hash_map.ts" /* 初始化雜湊表 */ const map = new Map(); + /* 新增操作 */ // 在雜湊表中新增鍵值對 (key, value) map.set(12836, '小哈'); @@ -155,24 +157,19 @@ map.set(15937, '小囉'); map.set(16750, '小算'); map.set(13276, '小法'); map.set(10583, '小鴨'); -console.info('\n新增完成後,雜湊表為\nKey -> Value'); -console.info(map); /* 查詢操作 */ // 向雜湊表中輸入鍵 key ,得到值 value let name = map.get(15937); -console.info('\n輸入學號 15937 ,查詢到姓名 ' + name); /* 刪除操作 */ // 在雜湊表中刪除鍵值對 (key, value) map.delete(10583); -console.info('\n刪除 10583 後,雜湊表為\nKey -> Value'); -console.info(map); ``` ```dart title="hash_map.dart" /* 初始化雜湊表 */ -Map map = {}; +final Map map = {}; /* 新增操作 */ // 在雜湊表中新增鍵值對 (key, value) @@ -184,7 +181,7 @@ map[10583] = "小鴨"; /* 查詢操作 */ // 向雜湊表中輸入鍵 key ,得到值 value -String? name = map[15937]; +final String? name = map[15937]; /* 刪除操作 */ // 在雜湊表中刪除鍵值對 (key, value) @@ -194,24 +191,24 @@ map.remove(10583); ```rust title="hash_map.rs" use std::collections::HashMap; -/* 初始化雜湊表 */ -let mut map: HashMap = HashMap::new(); +// 初始化雜湊表 +let mut map = HashMap::new(); -/* 新增操作 */ +// 新增操作 // 在雜湊表中新增鍵值對 (key, value) -map.insert(12836, "小哈".to_string()); -map.insert(15937, "小囉".to_string()); -map.insert(16750, "小算".to_string()); -map.insert(13276, "小法".to_string()); -map.insert(10583, "小鴨".to_string()); +map.insert(12836, "小哈"); +map.insert(15937, "小囉"); +map.insert(16750, "小算"); +map.insert(13276, "小法"); +map.insert(10583, "小鴨"); -/* 查詢操作 */ +// 查詢操作 // 向雜湊表中輸入鍵 key ,得到值 value -let _name: Option<&String> = map.get(&15937); +let name = map.get(&15937).copied().unwrap(); -/* 刪除操作 */ +// 刪除操作 // 在雜湊表中刪除鍵值對 (key, value) -let _removed_value: Option = map.remove(&10583); +_ = map.remove(&10583); ``` ```c title="hash_map.c" @@ -220,7 +217,7 @@ let _removed_value: Option = map.remove(&10583); ```kotlin title="hash_map.kt" /* 初始化雜湊表 */ -val map = HashMap() +val map = HashMap() /* 新增操作 */ // 在雜湊表中新增鍵值對 (key, value) @@ -269,52 +266,59 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20 # 走訪鍵值對 key->value for key, value in hmap.items(): print(key, "->", value) + # 單獨走訪鍵 key for key in hmap.keys(): print(key) + # 單獨走訪值 value -for value in hmap.values(): - print(value) +for val in hmap.values(): + print(val) ``` ```cpp title="hash_map.cpp" /* 走訪雜湊表 */ // 走訪鍵值對 key->value -for (auto kv: map) { +for (auto kv : map) { cout << kv.first << " -> " << kv.second << endl; } + // 使用迭代器走訪 key->value for (auto iter = map.begin(); iter != map.end(); iter++) { - cout << iter->first << "->" << iter->second << endl; + cout << iter->first << " -> " << iter->second << endl; } ``` ```java title="hash_map.java" /* 走訪雜湊表 */ // 走訪鍵值對 key->value -for (Map.Entry kv: map.entrySet()) { +for (Map.Entry kv : map.entrySet()) { System.out.println(kv.getKey() + " -> " + kv.getValue()); } + // 單獨走訪鍵 key -for (int key: map.keySet()) { +for (int key : map.keySet()) { System.out.println(key); } + // 單獨走訪值 value -for (String val: map.values()) { +for (String val : map.values()) { System.out.println(val); } ``` ```csharp title="hash_map.cs" /* 走訪雜湊表 */ -// 走訪鍵值對 Key->Value +// 走訪鍵值對 key->value foreach (var kv in map) { Console.WriteLine(kv.Key + " -> " + kv.Value); } + // 單獨走訪鍵 key foreach (int key in map.Keys) { Console.WriteLine(key); } + // 單獨走訪值 value foreach (string val in map.Values) { Console.WriteLine(val); @@ -327,10 +331,12 @@ foreach (string val in map.Values) { for key, value := range hmap { fmt.Println(key, "->", value) } + // 單獨走訪鍵 key for key := range hmap { fmt.Println(key) } + // 單獨走訪值 value for _, value := range hmap { fmt.Println(value) @@ -339,15 +345,17 @@ for _, value := range hmap { ```swift title="hash_map.swift" /* 走訪雜湊表 */ -// 走訪鍵值對 Key->Value +// 走訪鍵值對 key->value for (key, value) in map { print("\(key) -> \(value)") } -// 單獨走訪鍵 Key + +// 單獨走訪鍵 key for key in map.keys { print(key) } -// 單獨走訪值 Value + +// 單獨走訪值 value for value in map.values { print(value) } @@ -355,15 +363,17 @@ for value in map.values { ```javascript title="hash_map.js" /* 走訪雜湊表 */ -console.info('\n走訪鍵值對 Key->Value'); +// 走訪鍵值對 key->value for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\n單獨走訪鍵 Key'); + +// 單獨走訪鍵 key for (const k of map.keys()) { console.info(k); } -console.info('\n單獨走訪值 Value'); + +// 單獨走訪值 value for (const v of map.values()) { console.info(v); } @@ -371,15 +381,17 @@ for (const v of map.values()) { ```typescript title="hash_map.ts" /* 走訪雜湊表 */ -console.info('\n走訪鍵值對 Key->Value'); +// 走訪鍵值對 key->value for (const [k, v] of map.entries()) { console.info(k + ' -> ' + v); } -console.info('\n單獨走訪鍵 Key'); + +// 單獨走訪鍵 key for (const k of map.keys()) { console.info(k); } -console.info('\n單獨走訪值 Value'); + +// 單獨走訪值 value for (const v of map.values()) { console.info(v); } @@ -387,35 +399,29 @@ for (const v of map.values()) { ```dart title="hash_map.dart" /* 走訪雜湊表 */ -// 走訪鍵值對 Key->Value -map.forEach((key, value) { - print('$key -> $value'); -}); +// 走訪鍵值對 key->value +map.forEach((key, value) => print("$key -> $value")); -// 單獨走訪鍵 Key -map.keys.forEach((key) { - print(key); -}); +// 單獨走訪鍵 key +map.keys.forEach((key) => print(key)); -// 單獨走訪值 Value -map.values.forEach((value) { - print(value); -}); +// 單獨走訪值 value +map.values.forEach((value) => print(value)); ``` ```rust title="hash_map.rs" -/* 走訪雜湊表 */ -// 走訪鍵值對 Key->Value +// 走訪雜湊表 +// 走訪鍵值對 key->value for (key, value) in &map { println!("{key} -> {value}"); } -// 單獨走訪鍵 Key +// 單獨走訪鍵 key for key in map.keys() { println!("{key}"); } -// 單獨走訪值 Value +// 單獨走訪值 value for value in map.values() { println!("{value}"); } @@ -431,10 +437,12 @@ for value in map.values() { for ((key, value) in map) { println("$key -> $value") } + // 單獨走訪鍵 key for (key in map.keys) { println(key) } + // 單獨走訪值 value for (_val in map.values) { println(_val) @@ -454,4 +462,4 @@ hmap.values.each { |val| puts val } ``` -https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%96%B0%E5%A2%9E%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E6%96%B0%E5%A2%9E%E9%8D%B5%E5%80%BC%E5%B0%8D%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%9B%89%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B4%A8%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%B5%B0%E8%A8%AA%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20%23%20%E8%B5%B0%E8%A8%AA%E9%8D%B5%E5%80%BC%E5%B0%8D%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%E5%96%AE%E7%8D%A8%E8%B5%B0%E8%A8%AA%E9%8D%B5%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%96%AE%E7%8D%A8%E8%B5%B0%E8%A8%AA%E5%80%BC%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%96%B0%E5%A2%9E%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E9%9B%9C%E6%B9%8A%E8%A1%A8%E4%B8%AD%E6%96%B0%E5%A2%9E%E9%8D%B5%E5%80%BC%E5%B0%8D%20%28key%2C%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%9B%89%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B4%A8%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%B5%B0%E8%A8%AA%E9%9B%9C%E6%B9%8A%E8%A1%A8%0A%20%20%20%20%23%20%E8%B5%B0%E8%A8%AA%E9%8D%B5%E5%80%BC%E5%B0%8D%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20%E5%96%AE%E7%8D%A8%E8%B5%B0%E8%A8%AA%E9%8D%B5%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%96%AE%E7%8D%A8%E8%B5%B0%E8%A8%AA%E5%80%BC%20value%0A%20%20%20%20for%20val%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28val%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_heap/heap.md b/zh-hant/codes/snippets/chapter_heap/heap.md index c62de7af2..57610d057 100644 --- a/zh-hant/codes/snippets/chapter_heap/heap.md +++ b/zh-hant/codes/snippets/chapter_heap/heap.md @@ -17,15 +17,15 @@ heapq.heappush(max_heap, flag * 5) heapq.heappush(max_heap, flag * 4) # 獲取堆積頂元素 -peek: int = flag * max_heap[0] # 5 +peek: int = flag * max_heap[0] # 5 # 堆積頂元素出堆積 # 出堆積元素會形成一個從大到小的序列 -val = flag * heapq.heappop(max_heap) # 5 -val = flag * heapq.heappop(max_heap) # 4 -val = flag * heapq.heappop(max_heap) # 3 -val = flag * heapq.heappop(max_heap) # 2 -val = flag * heapq.heappop(max_heap) # 1 +val = flag * heapq.heappop(max_heap) # 5 +val = flag * heapq.heappop(max_heap) # 4 +val = flag * heapq.heappop(max_heap) # 3 +val = flag * heapq.heappop(max_heap) # 2 +val = flag * heapq.heappop(max_heap) # 1 # 獲取堆積大小 size: int = len(max_heap) @@ -34,6 +34,7 @@ size: int = len(max_heap) is_empty: bool = not max_heap # 輸入串列並建堆積 +# 時間複雜度為 O(n) ,而非 O(nlogn) min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) ``` @@ -70,6 +71,7 @@ int size = maxHeap.size(); bool isEmpty = maxHeap.empty(); /* 輸入串列並建堆積 */ +// 時間複雜度為 O(n) ,而非 O(nlogn) vector input{1, 3, 2, 5, 4}; minHeap = priority_queue, greater>(input.begin(), input.end()); ``` @@ -106,6 +108,7 @@ int size = maxHeap.size(); boolean isEmpty = maxHeap.isEmpty(); /* 輸入串列並建堆積 */ +// 時間複雜度為 O(n) ,而非 O(nlogn) minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); ``` @@ -124,15 +127,15 @@ maxHeap.Enqueue(5, 5); maxHeap.Enqueue(4, 4); /* 獲取堆積頂元素 */ -int peek = maxHeap.Peek();//5 +int peek = maxHeap.Peek(); // 5 /* 堆積頂元素出堆積 */ // 出堆積元素會形成一個從大到小的序列 -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +peek = maxHeap.Dequeue(); // 5 +peek = maxHeap.Dequeue(); // 4 +peek = maxHeap.Dequeue(); // 3 +peek = maxHeap.Dequeue(); // 2 +peek = maxHeap.Dequeue(); // 1 /* 獲取堆積大小 */ int size = maxHeap.Count; @@ -141,6 +144,7 @@ int size = maxHeap.Count; bool isEmpty = maxHeap.Count == 0; /* 輸入串列並建堆積 */ +// 時間複雜度為 O(n) ,而非 O(nlogn) minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); ``` @@ -149,14 +153,14 @@ minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); // 實現 heap.Interface 需要同時實現 sort.Interface type intHeap []any -// Push heap.Interface 的方法,實現推入元素到堆積 +// Push heap.Interface 的函式,實現推入元素到堆積 func (h *intHeap) Push(x any) { // Push 和 Pop 使用 pointer receiver 作為參數 // 因為它們不僅會對切片的內容進行調整,還會修改切片的長度。 *h = append(*h, x.(int)) } -// Pop heap.Interface 的方法,實現彈出堆積頂元素 +// Pop heap.Interface 的函式,實現彈出堆積頂元素 func (h *intHeap) Pop() any { // 待出堆積元素存放在最後 last := (*h)[len(*h)-1] @@ -164,18 +168,18 @@ func (h *intHeap) Pop() any { return last } -// Len sort.Interface 的方法 +// Len sort.Interface 的函式 func (h *intHeap) Len() int { return len(*h) } -// Less sort.Interface 的方法 +// Less sort.Interface 的函式 func (h *intHeap) Less(i, j int) bool { // 如果實現小頂堆積,則需要調整為小於號 return (*h)[i].(int) > (*h)[j].(int) } -// Swap sort.Interface 的方法 +// Swap sort.Interface 的函式 func (h *intHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } @@ -185,31 +189,31 @@ func (h *intHeap) Top() any { return (*h)[0] } -/* Driver Code */ func TestHeap(t *testing.T) { /* 初始化堆積 */ // 初始化大頂堆積 maxHeap := &intHeap{} heap.Init(maxHeap) /* 元素入堆積 */ - // 呼叫 heap.Interface 的方法,來新增元素 + // 呼叫 heap.Interface 的函式,來新增元素 heap.Push(maxHeap, 1) heap.Push(maxHeap, 3) heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) /* 獲取堆積頂元素 */ top := maxHeap.Top() fmt.Printf("堆積頂元素為 %d\n", top) /* 堆積頂元素出堆積 */ - // 呼叫 heap.Interface 的方法,來移除元素 - heap.Pop(maxHeap) // 5 - heap.Pop(maxHeap) // 4 - heap.Pop(maxHeap) // 3 - heap.Pop(maxHeap) // 2 - heap.Pop(maxHeap) // 1 + // 呼叫 heap.Interface 的函式,來移除元素 + fmt.Printf("出堆積元素為 %d\n", heap.Pop(maxHeap)) // 5 + fmt.Printf("出堆積元素為 %d\n", heap.Pop(maxHeap)) // 4 + fmt.Printf("出堆積元素為 %d\n", heap.Pop(maxHeap)) // 3 + fmt.Printf("出堆積元素為 %d\n", heap.Pop(maxHeap)) // 2 + fmt.Printf("出堆積元素為 %d\n", heap.Pop(maxHeap)) // 1 /* 獲取堆積大小 */ size := len(*maxHeap) @@ -222,8 +226,10 @@ func TestHeap(t *testing.T) { ``` ```swift title="heap.swift" +import HeapModule + /* 初始化堆積 */ -// Swift 的 Heap 型別同時支持最大堆積和最小堆積,且需要引入 swift-collections +// Swift 的 Heap 型別同時支持大頂堆積和小頂堆積,需要引入 swift-collections 包 var heap = Heap() /* 元素入堆積 */ @@ -234,7 +240,7 @@ heap.insert(5) heap.insert(4) /* 獲取堆積頂元素 */ -var peek = heap.max()! +var peek = heap.max() /* 堆積頂元素出堆積 */ peek = heap.removeMax() // 5 @@ -250,6 +256,7 @@ let size = heap.count let isEmpty = heap.isEmpty /* 輸入串列並建堆積 */ +// 時間複雜度為 O(n) ,而非 O(nlogn) let heap2 = Heap([1, 3, 2, 5, 4]) ``` @@ -266,12 +273,13 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +use std::{cmp::Reverse, collections::BinaryHeap}; /* 初始化堆積 */ // 初始化小頂堆積 -let mut min_heap = BinaryHeap::>::new(); +// Rust 的 BinaryHeap 是大頂堆積,小頂堆積需用 Reverse 包裝元素 +#[allow(unused_assignments)] +let mut min_heap = BinaryHeap::new(); // 初始化大頂堆積 let mut max_heap = BinaryHeap::new(); @@ -283,15 +291,15 @@ max_heap.push(5); max_heap.push(4); /* 獲取堆積頂元素 */ -let peek = max_heap.peek().unwrap(); // 5 +let peek = max_heap.peek().unwrap(); // 5 /* 堆積頂元素出堆積 */ // 出堆積元素會形成一個從大到小的序列 -let peek = max_heap.pop().unwrap(); // 5 -let peek = max_heap.pop().unwrap(); // 4 -let peek = max_heap.pop().unwrap(); // 3 -let peek = max_heap.pop().unwrap(); // 2 -let peek = max_heap.pop().unwrap(); // 1 +let peek = max_heap.pop().unwrap(); // 5 +let peek = max_heap.pop().unwrap(); // 4 +let peek = max_heap.pop().unwrap(); // 3 +let peek = max_heap.pop().unwrap(); // 2 +let peek = max_heap.pop().unwrap(); // 1 /* 獲取堆積大小 */ let size = max_heap.len(); @@ -300,7 +308,8 @@ let size = max_heap.len(); let is_empty = max_heap.is_empty(); /* 輸入串列並建堆積 */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +// 時間複雜度為 O(n) ,而非 O(nlogn) +min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); ``` ```c title="heap.c" @@ -339,7 +348,8 @@ val size = maxHeap.size val isEmpty = maxHeap.isEmpty() /* 輸入串列並建堆積 */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +// 時間複雜度為 O(n) ,而非 O(nlogn) +minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` ```ruby title="heap.rb" @@ -347,4 +357,4 @@ minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) ``` -https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E7%B5%84%E9%A0%90%E8%A8%AD%E5%AF%A6%E7%8F%BE%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E8%80%83%E6%85%AE%E5%B0%87%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B2%A0%E2%80%9D%E5%BE%8C%E5%86%8D%E5%85%A5%E5%A0%86%E7%A9%8D%EF%BC%8C%E9%80%99%E6%A8%A3%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%87%E5%A4%A7%E5%B0%8F%E9%97%9C%E4%BF%82%E9%A1%9B%E5%80%92%EF%BC%8C%E5%BE%9E%E8%80%8C%E5%AF%A6%E7%8F%BE%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%99%82%E5%B0%8D%E6%87%89%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%EF%BC%8Cflag%20%3D%20-1%20%E6%99%82%E5%B0%8D%E6%87%89%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%E7%A9%8D%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%A9%8D%E9%A0%82%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E7%A9%8D%E9%A0%82%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E7%A9%8D%E5%85%83%E7%B4%A0%E6%9C%83%E5%BD%A2%E6%88%90%E4%B8%80%E5%80%8B%E5%BE%9E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%A9%8D%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E5%A0%86%E7%A9%8D%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BC%B8%E5%85%A5%E4%B8%B2%E5%88%97%E4%B8%A6%E5%BB%BA%E5%A0%86%E7%A9%8D%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E7%B5%84%E9%A0%90%E8%A8%AD%E5%AF%A6%E7%8F%BE%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E8%80%83%E6%85%AE%E5%B0%87%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B2%A0%E2%80%9D%E5%BE%8C%E5%86%8D%E5%85%A5%E5%A0%86%E7%A9%8D%EF%BC%8C%E9%80%99%E6%A8%A3%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%87%E5%A4%A7%E5%B0%8F%E9%97%9C%E4%BF%82%E9%A1%9B%E5%80%92%EF%BC%8C%E5%BE%9E%E8%80%8C%E5%AF%A6%E7%8F%BE%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%99%82%E5%B0%8D%E6%87%89%E5%B0%8F%E9%A0%82%E5%A0%86%E7%A9%8D%EF%BC%8Cflag%20%3D%20-1%20%E6%99%82%E5%B0%8D%E6%87%89%E5%A4%A7%E9%A0%82%E5%A0%86%E7%A9%8D%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%E7%A9%8D%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%A9%8D%E9%A0%82%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E7%A9%8D%E9%A0%82%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E7%A9%8D%E5%85%83%E7%B4%A0%E6%9C%83%E5%BD%A2%E6%88%90%E4%B8%80%E5%80%8B%E5%BE%9E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E7%8D%B2%E5%8F%96%E5%A0%86%E7%A9%8D%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%B7%E5%A0%86%E7%A9%8D%E6%98%AF%E5%90%A6%E7%82%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BC%B8%E5%85%A5%E4%B8%B2%E5%88%97%E4%B8%A6%E5%BB%BA%E5%A0%86%E7%A9%8D%0A%20%20%20%20%23%20%E6%99%82%E9%96%93%E8%A4%87%E9%9B%9C%E5%BA%A6%E7%82%BA%20O%28n%29%20%EF%BC%8C%E8%80%8C%E9%9D%9E%20O%28nlogn%29%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/snippets/chapter_stack_and_queue/deque.md b/zh-hant/codes/snippets/chapter_stack_and_queue/deque.md index 42aeb43b6..23adeff0f 100644 --- a/zh-hant/codes/snippets/chapter_stack_and_queue/deque.md +++ b/zh-hant/codes/snippets/chapter_stack_and_queue/deque.md @@ -6,7 +6,7 @@ from collections import deque deq: deque[int] = deque() # 元素入列 -deq.append(2) # 新增至佇列尾 +deq.append(2) # 新增至佇列尾 deq.append(5) deq.append(4) deq.appendleft(3) # 新增至佇列首 @@ -18,7 +18,7 @@ rear: int = deq[-1] # 佇列尾元素 # 元素出列 pop_front: int = deq.popleft() # 佇列首元素出列 -pop_rear: int = deq.pop() # 佇列尾元素出列 +pop_rear: int = deq.pop() # 佇列尾元素出列 # 獲取雙向佇列的長度 size: int = len(deq) @@ -32,19 +32,19 @@ is_empty: bool = len(deq) == 0 deque deque; /* 元素入列 */ -deque.push_back(2); // 新增至佇列尾 +deque.push_back(2); // 新增至佇列尾 deque.push_back(5); deque.push_back(4); -deque.push_front(3); // 新增至佇列首 +deque.push_front(3); // 新增至佇列首 deque.push_front(1); /* 訪問元素 */ int front = deque.front(); // 佇列首元素 -int back = deque.back(); // 佇列尾元素 +int back = deque.back(); // 佇列尾元素 /* 元素出列 */ -deque.pop_front(); // 佇列首元素出列 -deque.pop_back(); // 佇列尾元素出列 +deque.pop_front(); // 佇列首元素出列 +deque.pop_back(); // 佇列尾元素出列 /* 獲取雙向佇列的長度 */ int size = deque.size(); @@ -58,19 +58,19 @@ bool empty = deque.empty(); Deque deque = new LinkedList<>(); /* 元素入列 */ -deque.offerLast(2); // 新增至佇列尾 +deque.offerLast(2); // 新增至佇列尾 deque.offerLast(5); deque.offerLast(4); -deque.offerFirst(3); // 新增至佇列首 +deque.offerFirst(3); // 新增至佇列首 deque.offerFirst(1); /* 訪問元素 */ -int peekFirst = deque.peekFirst(); // 佇列首元素 -int peekLast = deque.peekLast(); // 佇列尾元素 +int peekFirst = deque.peekFirst(); // 佇列首元素 +int peekLast = deque.peekLast(); // 佇列尾元素 /* 元素出列 */ -int popFirst = deque.pollFirst(); // 佇列首元素出列 -int popLast = deque.pollLast(); // 佇列尾元素出列 +int popFirst = deque.pollFirst(); // 佇列首元素出列 +int popLast = deque.pollLast(); // 佇列尾元素出列 /* 獲取雙向佇列的長度 */ int size = deque.size(); @@ -81,7 +81,7 @@ boolean isEmpty = deque.isEmpty(); ```csharp title="deque.cs" /* 初始化雙向佇列 */ -// 在 C# 中,將鏈結串列 LinkedList 看作雙向佇列來使用 +// 在 C# 中,將鏈結串列 LinkedList 當作雙向佇列來使用 LinkedList deque = new(); /* 元素入列 */ @@ -92,8 +92,8 @@ deque.AddFirst(3); // 新增至佇列首 deque.AddFirst(1); /* 訪問元素 */ -int peekFirst = deque.First.Value; // 佇列首元素 -int peekLast = deque.Last.Value; // 佇列尾元素 +int? peekFirst = deque.First?.Value; // 佇列首元素 +int? peekLast = deque.Last?.Value; // 佇列尾元素 /* 元素出列 */ deque.RemoveFirst(); // 佇列首元素出列 @@ -112,19 +112,19 @@ bool isEmpty = deque.Count == 0; deque := list.New() /* 元素入列 */ -deque.PushBack(2) // 新增至佇列尾 +deque.PushBack(2) // 新增至佇列尾 deque.PushBack(5) deque.PushBack(4) -deque.PushFront(3) // 新增至佇列首 +deque.PushFront(3) // 新增至佇列首 deque.PushFront(1) /* 訪問元素 */ front := deque.Front() // 佇列首元素 -rear := deque.Back() // 佇列尾元素 +rear := deque.Back() // 佇列尾元素 /* 元素出列 */ -deque.Remove(front) // 佇列首元素出列 -deque.Remove(rear) // 佇列尾元素出列 +deque.Remove(front) // 佇列首元素出列 +deque.Remove(rear) // 佇列尾元素出列 /* 獲取雙向佇列的長度 */ size := deque.Len() @@ -150,7 +150,7 @@ let peekFirst = deque.first! // 佇列首元素 let peekLast = deque.last! // 佇列尾元素 /* 元素出列 */ -// 使用 Array 模擬時 popFirst 的複雜度為 O(n) +// 使用 Array 模擬時 removeFirst 的複雜度為 O(n) let popFirst = deque.removeFirst() // 佇列首元素出列 let popLast = deque.removeLast() // 佇列尾元素出列 @@ -222,57 +222,53 @@ const isEmpty: boolean = size === 0; ```dart title="deque.dart" /* 初始化雙向佇列 */ // 在 Dart 中,Queue 被定義為雙向佇列 -Queue deque = Queue(); +final Queue deque = Queue(); /* 元素入列 */ -deque.addLast(2); // 新增至佇列尾 +deque.addLast(2); // 新增至佇列尾 deque.addLast(5); deque.addLast(4); deque.addFirst(3); // 新增至佇列首 deque.addFirst(1); /* 訪問元素 */ -int peekFirst = deque.first; // 佇列首元素 -int peekLast = deque.last; // 佇列尾元素 +final int peekFirst = deque.first; // 佇列首元素 +final int peekLast = deque.last; // 佇列尾元素 /* 元素出列 */ -int popFirst = deque.removeFirst(); // 佇列首元素出列 -int popLast = deque.removeLast(); // 佇列尾元素出列 +final int popFirst = deque.removeFirst(); // 佇列首元素出列 +final int popLast = deque.removeLast(); // 佇列尾元素出列 /* 獲取雙向佇列的長度 */ -int size = deque.length; +final int size = deque.length; /* 判斷雙向佇列是否為空 */ -bool isEmpty = deque.isEmpty; +final bool isEmpty = deque.isEmpty; ``` ```rust title="deque.rs" -/* 初始化雙向佇列 */ -let mut deque: VecDeque = VecDeque::new(); +// 初始化雙向佇列 +let mut deque: VecDeque = VecDeque::new(); /* 元素入列 */ -deque.push_back(2); // 新增至佇列尾 +deque.push_back(2); // 新增至佇列尾 deque.push_back(5); deque.push_back(4); deque.push_front(3); // 新增至佇列首 deque.push_front(1); -/* 訪問元素 */ -if let Some(front) = deque.front() { // 佇列首元素 -} -if let Some(rear) = deque.back() { // 佇列尾元素 -} +// 訪問元素 +let peek_first = deque.front().unwrap(); // 佇列首元素 +let peek_last = deque.back().unwrap(); // 佇列尾元素 -/* 元素出列 */ -if let Some(pop_front) = deque.pop_front() { // 佇列首元素出列 -} -if let Some(pop_rear) = deque.pop_back() { // 佇列尾元素出列 -} +// 元素出列 +let pop_first = deque.pop_front().unwrap(); // 佇列首元素出列 +let pop_last = deque.pop_back().unwrap(); // 佇列尾元素出列 -/* 獲取雙向佇列的長度 */ +// 獲取雙向佇列的長度 let size = deque.len(); -/* 判斷雙向佇列是否為空 */ +// 判斷雙向佇列是否為空 let is_empty = deque.is_empty(); ``` @@ -285,7 +281,7 @@ let is_empty = deque.is_empty(); val deque = LinkedList() /* 元素入列 */ -deque.offerLast(2) // 新增至佇列尾 +deque.offerLast(2) // 新增至佇列尾 deque.offerLast(5) deque.offerLast(4) deque.offerFirst(3) // 新增至佇列首 @@ -293,11 +289,11 @@ deque.offerFirst(1) /* 訪問元素 */ val peekFirst = deque.peekFirst() // 佇列首元素 -val peekLast = deque.peekLast() // 佇列尾元素 +val peekLast = deque.peekLast() // 佇列尾元素 /* 元素出列 */ val popFirst = deque.pollFirst() // 佇列首元素出列 -val popLast = deque.pollLast() // 佇列尾元素出列 +val popLast = deque.pollLast() // 佇列尾元素出列 /* 獲取雙向佇列的長度 */ val size = deque.size @@ -308,10 +304,10 @@ val isEmpty = deque.isEmpty() ```ruby title="deque.rb" # 初始化雙向佇列 -# Ruby 沒有內直的雙端佇列,只能把 Array 當作雙端佇列來使用 +# Ruby 沒有內建的雙端佇列,只能把 Array 當作雙端佇列來使用 deque = [] -# 元素如隊 +# 元素入列 deque << 2 deque << 5 deque << 4 @@ -324,7 +320,7 @@ peek_first = deque.first peek_last = deque.last # 元素出列 -# 請注意,由於是陣列, Array#shift 方法的時間複雜度為 O(n) +# 請注意,由於是陣列,Array#shift 方法的時間複雜度為 O(n) pop_front = deque.shift pop_back = deque.pop diff --git a/zh-hant/codes/snippets/chapter_stack_and_queue/queue.md b/zh-hant/codes/snippets/chapter_stack_and_queue/queue.md index 66cfd0acb..3ebf0311e 100644 --- a/zh-hant/codes/snippets/chapter_stack_and_queue/queue.md +++ b/zh-hant/codes/snippets/chapter_stack_and_queue/queue.md @@ -141,7 +141,7 @@ queue.append(4) let peek = queue.first! /* 元素出列 */ -// 由於是陣列,因此 removeFirst 的複雜度為 O(n) +// 使用 Array 模擬時 removeFirst 的複雜度為 O(n) let pop = queue.removeFirst() /* 獲取佇列的長度 */ @@ -174,7 +174,7 @@ const pop = queue.shift(); const size = queue.length; /* 判斷佇列是否為空 */ -const empty = queue.length === 0; +const isEmpty = queue.length === 0; ``` ```typescript title="queue.ts" @@ -200,13 +200,13 @@ const pop = queue.shift(); const size = queue.length; /* 判斷佇列是否為空 */ -const empty = queue.length === 0; +const isEmpty = queue.length === 0; ``` ```dart title="queue.dart" /* 初始化佇列 */ -// 在 Dart 中,佇列類別 Queue 是雙向佇列,也可作為佇列使用 -Queue queue = Queue(); +// 在 Dart 中,一般將雙向佇列類別 Queue 當作佇列使用 +final Queue queue = Queue(); /* 元素入列 */ queue.add(1); @@ -216,43 +216,41 @@ queue.add(5); queue.add(4); /* 訪問佇列首元素 */ -int peek = queue.first; +final int peek = queue.first; /* 元素出列 */ -int pop = queue.removeFirst(); +final int pop = queue.removeFirst(); /* 獲取佇列的長度 */ -int size = queue.length; +final int size = queue.length; /* 判斷佇列是否為空 */ -bool isEmpty = queue.isEmpty; +final bool isEmpty = queue.isEmpty; ``` ```rust title="queue.rs" -/* 初始化雙向佇列 */ -// 在 Rust 中使用雙向佇列作為普通佇列來使用 -let mut deque: VecDeque = VecDeque::new(); +// 初始化佇列 +// 在 Rust 中,一般將雙向佇列 VecDeque 看作佇列使用 +let mut queue: VecDeque = VecDeque::new(); -/* 元素入列 */ -deque.push_back(1); -deque.push_back(3); -deque.push_back(2); -deque.push_back(5); -deque.push_back(4); +// 元素入列 +queue.push_back(1); +queue.push_back(3); +queue.push_back(2); +queue.push_back(5); +queue.push_back(4); -/* 訪問佇列首元素 */ -if let Some(front) = deque.front() { -} +// 訪問佇列首元素 +let peek = queue.front().unwrap(); -/* 元素出列 */ -if let Some(pop) = deque.pop_front() { -} +// 元素出列 +let pop = queue.pop_front().unwrap(); -/* 獲取佇列的長度 */ -let size = deque.len(); +// 獲取佇列的長度 +let size = queue.len(); -/* 判斷佇列是否為空 */ -let is_empty = deque.is_empty(); +// 判斷佇列是否為空 +let is_empty = queue.is_empty(); ``` ```c title="queue.c" @@ -285,7 +283,7 @@ val isEmpty = queue.isEmpty() ```ruby title="queue.rb" # 初始化佇列 -# Ruby 內建的佇列(Thread::Queue) 沒有 peek 和走訪方法,可以把 Array 當作佇列來使用 +# Ruby 內建的佇列(Thread::Queue)沒有 peek 和走訪方法,可以把 Array 當作佇列來使用 queue = [] # 元素入列 @@ -299,7 +297,7 @@ queue.push(4) peek = queue.first # 元素出列 -# 清注意,由於是陣列,Array#shift 方法時間複雜度為 O(n) +# 請注意,由於是陣列,Array#shift 方法的時間複雜度為 O(n) pop = queue.shift # 獲取佇列的長度 diff --git a/zh-hant/codes/snippets/chapter_stack_and_queue/stack.md b/zh-hant/codes/snippets/chapter_stack_and_queue/stack.md index 25132c404..fd622ccb6 100644 --- a/zh-hant/codes/snippets/chapter_stack_and_queue/stack.md +++ b/zh-hant/codes/snippets/chapter_stack_and_queue/stack.md @@ -160,7 +160,7 @@ stack.push(5); stack.push(4); /* 訪問堆疊頂元素 */ -const peek = stack[stack.length-1]; +const peek = stack[stack.length - 1]; /* 元素出堆疊 */ const pop = stack.pop(); @@ -169,7 +169,7 @@ const pop = stack.pop(); const size = stack.length; /* 判斷是否為空 */ -const is_empty = stack.length === 0; +const isEmpty = stack.length === 0; ``` ```typescript title="stack.ts" @@ -194,13 +194,13 @@ const pop = stack.pop(); const size = stack.length; /* 判斷是否為空 */ -const is_empty = stack.length === 0; +const isEmpty = stack.length === 0; ``` ```dart title="stack.dart" /* 初始化堆疊 */ // Dart 沒有內建的堆疊類別,可以把 List 當作堆疊來使用 -List stack = []; +final List stack = []; /* 元素入堆疊 */ stack.add(1); @@ -210,40 +210,40 @@ stack.add(5); stack.add(4); /* 訪問堆疊頂元素 */ -int peek = stack.last; +final int peek = stack.last; /* 元素出堆疊 */ -int pop = stack.removeLast(); +final int pop = stack.removeLast(); /* 獲取堆疊的長度 */ -int size = stack.length; +final int size = stack.length; /* 判斷是否為空 */ -bool isEmpty = stack.isEmpty; +final bool isEmpty = stack.isEmpty; ``` ```rust title="stack.rs" -/* 初始化堆疊 */ -// 把 Vec 當作堆疊來使用 +// 初始化堆疊 +// 在 Rust 中,推薦將 Vec 當作堆疊來使用 let mut stack: Vec = Vec::new(); -/* 元素入堆疊 */ +// 元素入堆疊 stack.push(1); stack.push(3); stack.push(2); stack.push(5); stack.push(4); -/* 訪問堆疊頂元素 */ -let top = stack.last().unwrap(); +// 訪問堆疊頂元素 +let peek = stack.last().unwrap(); -/* 元素出堆疊 */ +// 元素出堆疊 let pop = stack.pop().unwrap(); -/* 獲取堆疊的長度 */ +// 獲取堆疊的長度 let size = stack.len(); -/* 判斷是否為空 */ +// 判斷堆疊是否為空 let is_empty = stack.is_empty(); ``` diff --git a/zh-hant/codes/snippets/chapter_tree/binary_tree.md b/zh-hant/codes/snippets/chapter_tree/binary_tree.md index b00b5dc2a..9fbc36e7a 100644 --- a/zh-hant/codes/snippets/chapter_tree/binary_tree.md +++ b/zh-hant/codes/snippets/chapter_tree/binary_tree.md @@ -133,7 +133,6 @@ impl TreeNode { /* 二元樹節點結構體 */ typedef struct TreeNode { int val; // 節點值 - int height; // 節點高度 struct TreeNode *left; // 左子節點指標 struct TreeNode *right; // 右子節點指標 } TreeNode; @@ -144,7 +143,6 @@ TreeNode *newTreeNode(int val) { node = (TreeNode *)malloc(sizeof(TreeNode)); node->val = val; - node->height = 0; node->left = NULL; node->right = NULL; return node; @@ -191,11 +189,11 @@ n2.right = n5 ```cpp title="binary_tree.cpp" /* 初始化二元樹 */ // 初始化節點 -TreeNode* n1 = new TreeNode(1); -TreeNode* n2 = new TreeNode(2); -TreeNode* n3 = new TreeNode(3); -TreeNode* n4 = new TreeNode(4); -TreeNode* n5 = new TreeNode(5); +TreeNode *n1 = new TreeNode(1); +TreeNode *n2 = new TreeNode(2); +TreeNode *n3 = new TreeNode(3); +TreeNode *n4 = new TreeNode(4); +TreeNode *n5 = new TreeNode(5); // 構建節點之間的引用(指標) n1->left = n2; n1->right = n3; @@ -204,6 +202,7 @@ n2->right = n5; ``` ```java title="binary_tree.java" +/* 初始化二元樹 */ // 初始化節點 TreeNode n1 = new TreeNode(1); TreeNode n2 = new TreeNode(2); @@ -248,6 +247,7 @@ n2.Right = n5 ``` ```swift title="binary_tree.swift" +/* 初始化二元樹 */ // 初始化節點 let n1 = TreeNode(x: 1) let n2 = TreeNode(x: 2) @@ -294,11 +294,11 @@ n2.right = n5; ```dart title="binary_tree.dart" /* 初始化二元樹 */ // 初始化節點 -TreeNode n1 = new TreeNode(1); -TreeNode n2 = new TreeNode(2); -TreeNode n3 = new TreeNode(3); -TreeNode n4 = new TreeNode(4); -TreeNode n5 = new TreeNode(5); +TreeNode n1 = TreeNode(1); +TreeNode n2 = TreeNode(2); +TreeNode n3 = TreeNode(3); +TreeNode n4 = TreeNode(4); +TreeNode n5 = TreeNode(5); // 構建節點之間的引用(指標) n1.left = n2; n1.right = n3; @@ -307,6 +307,7 @@ n2.right = n5; ``` ```rust title="binary_tree.rs" +/* 初始化二元樹 */ // 初始化節點 let n1 = TreeNode::new(1); let n2 = TreeNode::new(2); @@ -314,10 +315,10 @@ let n3 = TreeNode::new(3); let n4 = TreeNode::new(4); let n5 = TreeNode::new(5); // 構建節點之間的引用(指標) -n1.borrow_mut().left = Some(n2.clone()); -n1.borrow_mut().right = Some(n3); -n2.borrow_mut().left = Some(n4); -n2.borrow_mut().right = Some(n5); +n1.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().right = Some(Rc::clone(&n3)); +n2.borrow_mut().left = Some(Rc::clone(&n4)); +n2.borrow_mut().right = Some(Rc::clone(&n5)); ``` ```c title="binary_tree.c" @@ -336,6 +337,7 @@ n2->right = n5; ``` ```kotlin title="binary_tree.kt" +/* 初始化二元樹 */ // 初始化節點 val n1 = TreeNode(1) val n2 = TreeNode(2) @@ -370,27 +372,27 @@ https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%2 ```python title="binary_tree.py" # 插入與刪除節點 -p = TreeNode(0) +P = TreeNode(0) # 在 n1 -> n2 中間插入節點 P -n1.left = p -p.left = n2 +n1.left = P +P.left = n2 # 刪除節點 P n1.left = n2 ``` ```cpp title="binary_tree.cpp" /* 插入與刪除節點 */ -TreeNode* P = new TreeNode(0); +TreeNode *P = new TreeNode(0); // 在 n1 -> n2 中間插入節點 P n1->left = P; P->left = n2; // 刪除節點 P n1->left = n2; -// 釋放記憶體 -delete P; +delete P; // 釋放記憶體 ``` ```java title="binary_tree.java" +/* 插入與刪除節點 */ TreeNode P = new TreeNode(0); // 在 n1 -> n2 中間插入節點 P n1.left = P; @@ -420,6 +422,7 @@ n1.Left = n2 ``` ```swift title="binary_tree.swift" +/* 插入與刪除節點 */ let P = TreeNode(x: 0) // 在 n1 -> n2 中間插入節點 P n1.left = P @@ -430,7 +433,7 @@ n1.left = n2 ```javascript title="binary_tree.js" /* 插入與刪除節點 */ -let P = new TreeNode(0); +const P = new TreeNode(0); // 在 n1 -> n2 中間插入節點 P n1.left = P; P.left = n2; @@ -450,21 +453,23 @@ n1.left = n2; ```dart title="binary_tree.dart" /* 插入與刪除節點 */ -TreeNode P = new TreeNode(0); +TreeNode p = TreeNode(0); // 在 n1 -> n2 中間插入節點 P -n1.left = P; -P.left = n2; +n1.left = p; +p.left = n2; // 刪除節點 P n1.left = n2; ``` ```rust title="binary_tree.rs" +/* 插入與刪除節點 */ let p = TreeNode::new(0); // 在 n1 -> n2 中間插入節點 P -n1.borrow_mut().left = Some(p.clone()); -p.borrow_mut().left = Some(n2.clone()); -// 刪除節點 p -n1.borrow_mut().left = Some(n2); +p.borrow_mut().left = Some(Rc::clone(&n2)); +n1.borrow_mut().left = Some(Rc::clone(&p)); +// 刪除節點 P +drop(p); +n1.borrow_mut().left = Some(Rc::clone(&n2)); ``` ```c title="binary_tree.c" @@ -480,6 +485,7 @@ free(P); ``` ```kotlin title="binary_tree.kt" +/* 插入與刪除節點 */ val P = TreeNode(0) // 在 n1 -> n2 中間插入節點 P n1.left = P @@ -499,4 +505,4 @@ n1.left = n2 ``` -https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%85%83%E6%A8%B9%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%85%83%E6%A8%B9%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E7%AF%80%E9%BB%9E%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%A7%8B%E5%BB%BA%E7%AF%80%E9%BB%9E%E4%B9%8B%E9%96%93%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E6%A8%99%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E8%88%87%E5%88%AA%E9%99%A4%E7%AF%80%E9%BB%9E%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%96%93%E6%8F%92%E5%85%A5%E7%AF%80%E9%BB%9E%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E7%AF%80%E9%BB%9E%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false +https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%85%83%E6%A8%B9%E7%AF%80%E9%BB%9E%E9%A1%9E%E5%88%A5%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E7%AF%80%E9%BB%9E%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E7%AF%80%E9%BB%9E%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%85%83%E6%A8%B9%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E7%AF%80%E9%BB%9E%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%A7%8B%E5%BB%BA%E7%AF%80%E9%BB%9E%E4%B9%8B%E9%96%93%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E6%A8%99%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E8%88%87%E5%88%AA%E9%99%A4%E7%AF%80%E9%BB%9E%0A%20%20%20%20P%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%96%93%E6%8F%92%E5%85%A5%E7%AF%80%E9%BB%9E%20P%0A%20%20%20%20n1.left%20%3D%20P%0A%20%20%20%20P.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%AA%E9%99%A4%E7%AF%80%E9%BB%9E%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false diff --git a/zh-hant/codes/swift/chapter_stack_and_queue/deque.swift b/zh-hant/codes/swift/chapter_stack_and_queue/deque.swift index fc6f6dcbc..fd29ea503 100644 --- a/zh-hant/codes/swift/chapter_stack_and_queue/deque.swift +++ b/zh-hant/codes/swift/chapter_stack_and_queue/deque.swift @@ -27,7 +27,7 @@ enum Deque { print("佇列尾元素 peekLast = \(peekLast)") /* 元素出列 */ - // 使用 Array 模擬時 popFirst 的複雜度為 O(n) + // 使用 Array 模擬時 removeFirst 的複雜度為 O(n) let popFirst = deque.removeFirst() print("佇列首出列元素 popFirst = \(popFirst),佇列首出列後 deque = \(deque)") let popLast = deque.removeLast() diff --git a/zh-hant/codes/swift/chapter_stack_and_queue/queue.swift b/zh-hant/codes/swift/chapter_stack_and_queue/queue.swift index 32098dba1..67635a114 100644 --- a/zh-hant/codes/swift/chapter_stack_and_queue/queue.swift +++ b/zh-hant/codes/swift/chapter_stack_and_queue/queue.swift @@ -25,7 +25,7 @@ enum Queue { print("佇列首元素 peek = \(peek)") /* 元素出列 */ - // 使用 Array 模擬時 pop 的複雜度為 O(n) + // 使用 Array 模擬時 removeFirst 的複雜度為 O(n) let pop = queue.removeFirst() print("出列元素 pop = \(pop),出列後 queue = \(queue)") diff --git a/zh-hant/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts b/zh-hant/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts index dee0629d6..15578cac8 100644 --- a/zh-hant/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/zh-hant/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -6,8 +6,8 @@ /* 雙向鏈結串列節點 */ class ListNode { - prev: ListNode; // 前驅節點引用 (指標) - next: ListNode; // 後繼節點引用 (指標) + prev: ListNode | null; // 前驅節點引用 (指標) + next: ListNode | null; // 後繼節點引用 (指標) val: number; // 節點值 constructor(val: number) {