From bcd86fc1ed6b2da98ecfc6f3322744a5993b6375 Mon Sep 17 00:00:00 2001 From: Yudong Jin Date: Mon, 16 Nov 2026 05:23:41 +0800 Subject: [PATCH] Cite demo-source regions for heap operations and the linked-list node classes (#2036) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Batch 3a of the runnable-snippets plan. heap_operations now cites the heap demos in Python, C++, Java, C#, Go, Swift, Rust and Kotlin; the demos call the library directly instead of push/pop helpers and print each popped value. list_node_class cites each language's shared ListNode (Swift stays literal) and doubly_list_node_class cites linkedlist_deque (Go stays literal). Node comments adopt reviewed source wording, Rust and Swift get import regions, the Ruby typo 前躯 becomes 前驱, and the TypeScript doubly node fields become nullable. en, ja, ko and zh-hant are regenerated; ru is synced by hand. Co-Authored-By: Claude Opus 5.5 --- .../linkedlist_deque.c | 2 + codes/c/utils/list_node.h | 2 + codes/cpp/chapter_heap/heap.cpp | 68 ++-- .../linkedlist_deque.cpp | 2 + codes/cpp/utils/list_node.hpp | 6 +- codes/csharp/chapter_heap/heap.cs | 65 ++-- .../linkedlist_deque.cs | 4 +- codes/csharp/utils/ListNode.cs | 8 +- .../linkedlist_deque.dart | 2 + codes/dart/utils/list_node.dart | 8 +- codes/go/chapter_heap/heap.go | 3 + codes/go/chapter_heap/heap_test.go | 40 +- codes/go/pkg/list_node.go | 9 +- codes/java/chapter_heap/heap.java | 63 ++-- .../linkedlist_deque.java | 4 +- codes/java/utils/ListNode.java | 8 +- .../linkedlist_deque.js | 2 + codes/javascript/modules/ListNode.js | 2 + codes/kotlin/chapter_heap/heap.kt | 64 ++-- .../linkedlist_deque.kt | 4 +- codes/kotlin/utils/ListNode.kt | 8 +- codes/python/chapter_heap/heap.py | 67 ++-- .../linkedlist_deque.py | 4 +- codes/python/modules/list_node.py | 4 +- .../linkedlist_deque.rb | 6 +- codes/ruby/utils/list_node.rb | 2 + codes/rust/chapter_heap/heap.rs | 72 ++-- .../linkedlist_deque.rs | 4 + codes/rust/src/include/list_node.rs | 12 +- .../linked_list.md | 244 ++----------- codes/snippets/chapter_heap/heap.md | 341 +++++------------- codes/swift/chapter_heap/heap.swift | 64 ++-- .../linkedlist_deque.swift | 2 + .../linkedlist_deque.ts | 6 +- codes/typescript/modules/ListNode.ts | 6 +- .../linkedlist_deque.c | 2 + en/codes/c/utils/list_node.h | 2 + en/codes/cpp/chapter_heap/heap.cpp | 68 ++-- .../linkedlist_deque.cpp | 2 + en/codes/cpp/utils/list_node.hpp | 6 +- en/codes/csharp/chapter_heap/heap.cs | 65 ++-- .../linkedlist_deque.cs | 4 +- en/codes/csharp/utils/ListNode.cs | 8 +- .../linkedlist_deque.dart | 2 + en/codes/dart/utils/list_node.dart | 8 +- en/codes/go/chapter_heap/heap.go | 3 + en/codes/go/chapter_heap/heap_test.go | 40 +- en/codes/go/pkg/list_node.go | 9 +- en/codes/java/chapter_heap/heap.java | 63 ++-- .../linkedlist_deque.java | 4 +- en/codes/java/utils/ListNode.java | 8 +- .../linkedlist_deque.js | 2 + en/codes/javascript/modules/ListNode.js | 2 + en/codes/kotlin/chapter_heap/heap.kt | 64 ++-- .../linkedlist_deque.kt | 4 +- en/codes/kotlin/utils/ListNode.kt | 8 +- en/codes/python/chapter_heap/heap.py | 67 ++-- .../linkedlist_deque.py | 4 +- en/codes/python/modules/list_node.py | 2 + .../linkedlist_deque.rb | 4 +- en/codes/ruby/utils/list_node.rb | 2 + en/codes/rust/chapter_heap/heap.rs | 72 ++-- .../linkedlist_deque.rs | 4 + en/codes/rust/src/include/list_node.rs | 12 +- .../linked_list.md | 244 ++----------- en/codes/snippets/chapter_heap/heap.md | 341 +++++------------- en/codes/swift/chapter_heap/heap.swift | 64 ++-- .../linkedlist_deque.swift | 2 + .../linkedlist_deque.ts | 6 +- en/codes/typescript/modules/ListNode.ts | 6 +- .../linkedlist_deque.c | 2 + ja/codes/c/utils/list_node.h | 2 + ja/codes/cpp/chapter_heap/heap.cpp | 68 ++-- .../linkedlist_deque.cpp | 2 + ja/codes/cpp/utils/list_node.hpp | 6 +- ja/codes/csharp/chapter_heap/heap.cs | 65 ++-- .../linkedlist_deque.cs | 4 +- ja/codes/csharp/utils/ListNode.cs | 8 +- .../linkedlist_deque.dart | 2 + ja/codes/dart/utils/list_node.dart | 8 +- ja/codes/go/chapter_heap/heap.go | 3 + ja/codes/go/chapter_heap/heap_test.go | 40 +- ja/codes/go/pkg/list_node.go | 9 +- ja/codes/java/chapter_heap/heap.java | 63 ++-- .../linkedlist_deque.java | 4 +- ja/codes/java/utils/ListNode.java | 8 +- .../linkedlist_deque.js | 2 + ja/codes/javascript/modules/ListNode.js | 2 + ja/codes/kotlin/chapter_heap/heap.kt | 64 ++-- .../linkedlist_deque.kt | 4 +- ja/codes/kotlin/utils/ListNode.kt | 8 +- ja/codes/python/chapter_heap/heap.py | 67 ++-- .../linkedlist_deque.py | 4 +- ja/codes/python/modules/list_node.py | 4 +- .../linkedlist_deque.rb | 4 +- ja/codes/ruby/utils/list_node.rb | 2 + ja/codes/rust/chapter_heap/heap.rs | 72 ++-- .../linkedlist_deque.rs | 4 + ja/codes/rust/src/include/list_node.rs | 12 +- .../linked_list.md | 244 ++----------- ja/codes/snippets/chapter_heap/heap.md | 341 +++++------------- ja/codes/swift/chapter_heap/heap.swift | 64 ++-- .../linkedlist_deque.swift | 2 + .../linkedlist_deque.ts | 6 +- ja/codes/typescript/modules/ListNode.ts | 6 +- .../linkedlist_deque.c | 2 + ko/codes/c/utils/list_node.h | 2 + ko/codes/cpp/chapter_heap/heap.cpp | 68 ++-- .../linkedlist_deque.cpp | 2 + ko/codes/cpp/utils/list_node.hpp | 6 +- ko/codes/csharp/chapter_heap/heap.cs | 65 ++-- .../linkedlist_deque.cs | 4 +- ko/codes/csharp/utils/ListNode.cs | 8 +- .../linkedlist_deque.dart | 2 + ko/codes/dart/utils/list_node.dart | 8 +- ko/codes/go/chapter_heap/heap.go | 3 + ko/codes/go/chapter_heap/heap_test.go | 40 +- ko/codes/go/pkg/list_node.go | 9 +- ko/codes/java/chapter_heap/heap.java | 63 ++-- .../linkedlist_deque.java | 4 +- ko/codes/java/utils/ListNode.java | 8 +- .../linkedlist_deque.js | 2 + ko/codes/javascript/modules/ListNode.js | 2 + ko/codes/kotlin/chapter_heap/heap.kt | 64 ++-- .../linkedlist_deque.kt | 4 +- ko/codes/kotlin/utils/ListNode.kt | 8 +- ko/codes/python/chapter_heap/heap.py | 67 ++-- .../linkedlist_deque.py | 4 +- ko/codes/python/modules/list_node.py | 4 +- .../linkedlist_deque.rb | 4 +- ko/codes/ruby/utils/list_node.rb | 2 + ko/codes/rust/chapter_heap/heap.rs | 72 ++-- .../linkedlist_deque.rs | 4 + ko/codes/rust/src/include/list_node.rs | 12 +- .../linked_list.md | 244 ++----------- ko/codes/snippets/chapter_heap/heap.md | 341 +++++------------- ko/codes/swift/chapter_heap/heap.swift | 64 ++-- .../linkedlist_deque.swift | 2 + .../linkedlist_deque.ts | 6 +- ko/codes/typescript/modules/ListNode.ts | 6 +- .../linkedlist_deque.c | 2 + ru/codes/c/utils/list_node.h | 2 + ru/codes/cpp/chapter_heap/heap.cpp | 68 ++-- .../linkedlist_deque.cpp | 2 + ru/codes/cpp/utils/list_node.hpp | 6 +- ru/codes/csharp/chapter_heap/heap.cs | 65 ++-- .../linkedlist_deque.cs | 4 +- ru/codes/csharp/utils/ListNode.cs | 8 +- .../linkedlist_deque.dart | 2 + ru/codes/dart/utils/list_node.dart | 8 +- ru/codes/go/chapter_heap/heap.go | 3 + ru/codes/go/chapter_heap/heap_test.go | 40 +- ru/codes/go/pkg/list_node.go | 9 +- ru/codes/java/chapter_heap/heap.java | 63 ++-- .../linkedlist_deque.java | 4 +- ru/codes/java/utils/ListNode.java | 8 +- .../linkedlist_deque.js | 2 + ru/codes/javascript/modules/ListNode.js | 2 + ru/codes/kotlin/chapter_heap/heap.kt | 64 ++-- .../linkedlist_deque.kt | 4 +- ru/codes/kotlin/utils/ListNode.kt | 8 +- ru/codes/python/chapter_heap/heap.py | 67 ++-- .../linkedlist_deque.py | 4 +- ru/codes/python/modules/list_node.py | 4 +- .../linkedlist_deque.rb | 4 +- ru/codes/ruby/utils/list_node.rb | 2 + ru/codes/rust/chapter_heap/heap.rs | 72 ++-- .../linkedlist_deque.rs | 4 + ru/codes/rust/src/include/list_node.rs | 12 +- .../linked_list.md | 244 ++----------- ru/codes/snippets/chapter_heap/heap.md | 341 +++++------------- ru/codes/swift/chapter_heap/heap.swift | 64 ++-- .../linkedlist_deque.swift | 2 + .../linkedlist_deque.ts | 6 +- ru/codes/typescript/modules/ListNode.ts | 6 +- .../linkedlist_deque.c | 2 + zh-hant/codes/c/utils/list_node.h | 2 + zh-hant/codes/cpp/chapter_heap/heap.cpp | 68 ++-- .../linkedlist_deque.cpp | 2 + zh-hant/codes/cpp/utils/list_node.hpp | 6 +- zh-hant/codes/csharp/chapter_heap/heap.cs | 65 ++-- .../linkedlist_deque.cs | 4 +- zh-hant/codes/csharp/utils/ListNode.cs | 8 +- .../linkedlist_deque.dart | 2 + zh-hant/codes/dart/utils/list_node.dart | 8 +- zh-hant/codes/go/chapter_heap/heap.go | 3 + zh-hant/codes/go/chapter_heap/heap_test.go | 40 +- zh-hant/codes/go/pkg/list_node.go | 9 +- zh-hant/codes/java/chapter_heap/heap.java | 63 ++-- .../linkedlist_deque.java | 4 +- zh-hant/codes/java/utils/ListNode.java | 8 +- .../linkedlist_deque.js | 2 + zh-hant/codes/javascript/modules/ListNode.js | 2 + zh-hant/codes/kotlin/chapter_heap/heap.kt | 64 ++-- .../linkedlist_deque.kt | 4 +- zh-hant/codes/kotlin/utils/ListNode.kt | 8 +- zh-hant/codes/python/chapter_heap/heap.py | 67 ++-- .../linkedlist_deque.py | 4 +- zh-hant/codes/python/modules/list_node.py | 4 +- .../linkedlist_deque.rb | 6 +- zh-hant/codes/ruby/utils/list_node.rb | 2 + zh-hant/codes/rust/chapter_heap/heap.rs | 72 ++-- .../linkedlist_deque.rs | 4 + zh-hant/codes/rust/src/include/list_node.rs | 12 +- .../linked_list.md | 244 ++----------- zh-hant/codes/snippets/chapter_heap/heap.md | 341 +++++------------- zh-hant/codes/swift/chapter_heap/heap.swift | 64 ++-- .../linkedlist_deque.swift | 2 + .../linkedlist_deque.ts | 6 +- zh-hant/codes/typescript/modules/ListNode.ts | 6 +- 210 files changed, 3061 insertions(+), 4177 deletions(-) diff --git a/codes/c/chapter_stack_and_queue/linkedlist_deque.c b/codes/c/chapter_stack_and_queue/linkedlist_deque.c index 367554cc7..522a19556 100644 --- a/codes/c/chapter_stack_and_queue/linkedlist_deque.c +++ b/codes/c/chapter_stack_and_queue/linkedlist_deque.c @@ -6,6 +6,7 @@ #include "../utils/common.h" +// [region]{doubly_list_node} /* 双向链表节点 */ typedef struct DoublyListNode { int val; // 节点值 @@ -21,6 +22,7 @@ DoublyListNode *newDoublyListNode(int num) { new->prev = NULL; return new; } +// [endregion]{doubly_list_node} /* 析构函数 */ void delDoublyListNode(DoublyListNode *node) { diff --git a/codes/c/utils/list_node.h b/codes/c/utils/list_node.h index 78db68784..66ef16133 100644 --- a/codes/c/utils/list_node.h +++ b/codes/c/utils/list_node.h @@ -11,6 +11,7 @@ extern "C" { #endif +// [region]{list_node} /* 链表节点结构体 */ typedef struct ListNode { int val; // 节点值 @@ -25,6 +26,7 @@ ListNode *newListNode(int val) { node->next = NULL; return node; } +// [endregion]{list_node} /* 将数组反序列化为链表 */ ListNode *arrToLinkedList(const int *arr, size_t size) { diff --git a/codes/cpp/chapter_heap/heap.cpp b/codes/cpp/chapter_heap/heap.cpp index 84f70bb49..0b29d74d8 100644 --- a/codes/cpp/chapter_heap/heap.cpp +++ b/codes/cpp/chapter_heap/heap.cpp @@ -6,59 +6,75 @@ #include "../utils/common.hpp" -void testPush(priority_queue &heap, int val) { - heap.push(val); // 元素入堆 - cout << "\n元素 " << val << " 入堆后" << endl; - printHeap(heap); -} - -void testPop(priority_queue &heap) { - int val = heap.top(); - heap.pop(); - cout << "\n堆顶元素 " << val << " 出堆后" << endl; - printHeap(heap); -} - /* Driver Code */ int main() { + // [region]{init} /* 初始化堆 */ // 初始化小顶堆 - // priority_queue, greater> minHeap; + priority_queue, greater> minHeap; // 初始化大顶堆 priority_queue, less> maxHeap; + // [endregion]{init} cout << "\n以下测试样例为大顶堆" << endl; + // [region]{push} /* 元素入堆 */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.push(1); + maxHeap.push(3); + maxHeap.push(2); + maxHeap.push(5); + maxHeap.push(4); + // [endregion]{push} + printHeap(maxHeap); + // [region]{peek} /* 获取堆顶元素 */ - int peek = maxHeap.top(); + int peek = maxHeap.top(); // 5 + // [endregion]{peek} cout << "\n堆顶元素为 " << peek << endl; + // [region]{pop_1} /* 堆顶元素出堆 */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // 出堆元素会形成一个从大到小的序列 + maxHeap.pop(); // 5 + // [endregion]{pop_1} + printHeap(maxHeap); + // [region]{pop_2} + maxHeap.pop(); // 4 + // [endregion]{pop_2} + printHeap(maxHeap); + // [region]{pop_3} + maxHeap.pop(); // 3 + // [endregion]{pop_3} + printHeap(maxHeap); + // [region]{pop_4} + maxHeap.pop(); // 2 + // [endregion]{pop_4} + printHeap(maxHeap); + // [region]{pop_5} + maxHeap.pop(); // 1 + // [endregion]{pop_5} + printHeap(maxHeap); + // [region]{size} /* 获取堆大小 */ int size = maxHeap.size(); + // [endregion]{size} cout << "\n堆元素数量为 " << size << endl; + // [region]{is_empty} /* 判断堆是否为空 */ bool isEmpty = maxHeap.empty(); + // [endregion]{is_empty} cout << "\n堆是否为空 " << isEmpty << endl; + // [region]{heapify} /* 输入列表并建堆 */ // 时间复杂度为 O(n) ,而非 O(nlogn) vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); + minHeap = priority_queue, greater>(input.begin(), input.end()); + // [endregion]{heapify} cout << "输入列表并建立小顶堆后" << endl; printHeap(minHeap); diff --git a/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp b/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp index 0fb057e28..41fc4dcb2 100644 --- a/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp +++ b/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp @@ -6,6 +6,7 @@ #include "../utils/common.hpp" +// [region]{doubly_list_node} /* 双向链表节点 */ struct DoublyListNode { int val; // 节点值 @@ -14,6 +15,7 @@ struct DoublyListNode { DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { } }; +// [endregion]{doubly_list_node} /* 基于双向链表实现的双向队列 */ class LinkedListDeque { diff --git a/codes/cpp/utils/list_node.hpp b/codes/cpp/utils/list_node.hpp index 7526fe608..cdeaff983 100644 --- a/codes/cpp/utils/list_node.hpp +++ b/codes/cpp/utils/list_node.hpp @@ -11,13 +11,15 @@ using namespace std; +// [region]{list_node} /* 链表节点 */ struct ListNode { - int val; - ListNode *next; + int val; // 节点值 + ListNode *next; // 后继节点指针 ListNode(int x) : val(x), next(nullptr) { } }; +// [endregion]{list_node} /* 将列表反序列化为链表 */ ListNode *vecToLinkedList(vector list) { diff --git a/codes/csharp/chapter_heap/heap.cs b/codes/csharp/chapter_heap/heap.cs index f50ceba3a..ee56e4f37 100644 --- a/codes/csharp/chapter_heap/heap.cs +++ b/codes/csharp/chapter_heap/heap.cs @@ -7,57 +7,72 @@ namespace hello_algo.chapter_heap; public class heap { - void TestPush(PriorityQueue heap, int val) { - heap.Enqueue(val, val); // 元素入堆 - Console.WriteLine($"\n元素 {val} 入堆后\n"); - PrintUtil.PrintHeap(heap); - } - - void TestPop(PriorityQueue heap) { - int val = heap.Dequeue(); // 堆顶元素出堆 - Console.WriteLine($"\n堆顶元素 {val} 出堆后\n"); - PrintUtil.PrintHeap(heap); - } - [Test] public void Test() { + // [region]{init} /* 初始化堆 */ // 初始化小顶堆 PriorityQueue minHeap = new(); // 初始化大顶堆(使用 lambda 表达式修改 Comparer 即可) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + // [endregion]{init} Console.WriteLine("以下测试样例为大顶堆"); + // [region]{push} /* 元素入堆 */ - TestPush(maxHeap, 1); - TestPush(maxHeap, 3); - TestPush(maxHeap, 2); - TestPush(maxHeap, 5); - TestPush(maxHeap, 4); + maxHeap.Enqueue(1, 1); + maxHeap.Enqueue(3, 3); + maxHeap.Enqueue(2, 2); + maxHeap.Enqueue(5, 5); + maxHeap.Enqueue(4, 4); + // [endregion]{push} + PrintUtil.PrintHeap(maxHeap); + // [region]{peek} /* 获取堆顶元素 */ - int peek = maxHeap.Peek(); + int peek = maxHeap.Peek(); // 5 + // [endregion]{peek} Console.WriteLine($"堆顶元素为 {peek}"); + // [region]{pop_1} /* 堆顶元素出堆 */ // 出堆元素会形成一个从大到小的序列 - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); + peek = maxHeap.Dequeue(); // 5 + // [endregion]{pop_1} + Console.WriteLine(peek); + // [region]{pop_2} + peek = maxHeap.Dequeue(); // 4 + // [endregion]{pop_2} + Console.WriteLine(peek); + // [region]{pop_3} + peek = maxHeap.Dequeue(); // 3 + // [endregion]{pop_3} + Console.WriteLine(peek); + // [region]{pop_4} + peek = maxHeap.Dequeue(); // 2 + // [endregion]{pop_4} + Console.WriteLine(peek); + // [region]{pop_5} + peek = maxHeap.Dequeue(); // 1 + // [endregion]{pop_5} + Console.WriteLine(peek); + // [region]{size} /* 获取堆大小 */ int size = maxHeap.Count; + // [endregion]{size} Console.WriteLine($"堆元素数量为 {size}"); + // [region]{is_empty} /* 判断堆是否为空 */ bool isEmpty = maxHeap.Count == 0; + // [endregion]{is_empty} Console.WriteLine($"堆是否为空 {isEmpty}"); + // [region]{heapify} /* 输入列表并建堆 */ - var list = new int[] { 1, 3, 2, 5, 4 }; - minHeap = new PriorityQueue(list.Select(x => (x, x))); + minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); + // [endregion]{heapify} Console.WriteLine("输入列表并建立小顶堆后"); PrintUtil.PrintHeap(minHeap); } diff --git a/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs b/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs index e87513eb4..10268f037 100644 --- a/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs +++ b/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs @@ -6,12 +6,14 @@ namespace hello_algo.chapter_stack_and_queue; +// [region]{doubly_list_node} /* 双向链表节点 */ public class ListNode(int val) { - public int val = val; // 节点值 + public int val = val; // 节点值 public ListNode? next = null; // 后继节点引用 public ListNode? prev = null; // 前驱节点引用 } +// [endregion]{doubly_list_node} /* 基于双向链表实现的双向队列 */ public class LinkedListDeque { diff --git a/codes/csharp/utils/ListNode.cs b/codes/csharp/utils/ListNode.cs index 3205b49ed..9657399c0 100644 --- a/codes/csharp/utils/ListNode.cs +++ b/codes/csharp/utils/ListNode.cs @@ -4,10 +4,12 @@ namespace hello_algo.utils; +// [region]{list_node} /* 链表节点 */ public class ListNode(int x) { - public int val = x; - public ListNode? next; + public int val = x; // 节点值 + public ListNode? next; // 指向下一节点的引用 +// [endregion]{list_node} /* 将数组反序列化为链表 */ public static ListNode? ArrToLinkedList(int[] arr) { @@ -29,4 +31,6 @@ public class ListNode(int x) { } return string.Join("->", list); } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart b/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart index 3ecc4abaa..cac2889dc 100644 --- a/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart +++ b/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart @@ -4,6 +4,7 @@ * Author: liuyuxin (gvenusleo@gmail.com) */ +// [region]{doubly_list_node} /* 双向链表节点 */ class ListNode { int val; // 节点值 @@ -12,6 +13,7 @@ class ListNode { ListNode(this.val, {this.next, this.prev}); } +// [endregion]{doubly_list_node} /* 基于双向链表实现的双向对列 */ class LinkedListDeque { diff --git a/codes/dart/utils/list_node.dart b/codes/dart/utils/list_node.dart index b77f61d1c..c3de7203b 100644 --- a/codes/dart/utils/list_node.dart +++ b/codes/dart/utils/list_node.dart @@ -4,13 +4,15 @@ * Author: Jefferson (JeffersonHuang77@gmail.com) */ +// [region]{list_node} /* 链表节点 */ class ListNode { - int val; - ListNode? next; + int val; // 节点值 + ListNode? next; // 指向下一节点的引用 - ListNode(this.val, [this.next]); + ListNode(this.val, [this.next]); // 构造函数 } +// [endregion]{list_node} /* 将列表反序列化为链表 */ ListNode? listToLinkedList(List list) { diff --git a/codes/go/chapter_heap/heap.go b/codes/go/chapter_heap/heap.go index 56a67f5cc..4124daf64 100644 --- a/codes/go/chapter_heap/heap.go +++ b/codes/go/chapter_heap/heap.go @@ -4,6 +4,7 @@ package chapter_heap +// [region]{int_heap} // Go 语言中可以通过实现 heap.Interface 来构建整数大顶堆 // 实现 heap.Interface 需要同时实现 sort.Interface type intHeap []any @@ -43,3 +44,5 @@ func (h *intHeap) Swap(i, j int) { func (h *intHeap) Top() any { return (*h)[0] } + +// [endregion]{int_heap} diff --git a/codes/go/chapter_heap/heap_test.go b/codes/go/chapter_heap/heap_test.go index 4b84a05e5..974a25ebb 100644 --- a/codes/go/chapter_heap/heap_test.go +++ b/codes/go/chapter_heap/heap_test.go @@ -13,42 +13,32 @@ import ( . "github.com/krahets/hello-algo/pkg" ) -func testPush(h *intHeap, val int) { - // 调用 heap.Interface 的函数,来添加元素 - heap.Push(h, val) - fmt.Printf("\n元素 %d 入堆后 \n", val) - PrintHeap(*h) -} - -func testPop(h *intHeap) { - // 调用 heap.Interface 的函数,来移除元素 - val := heap.Pop(h) - fmt.Printf("\n堆顶元素 %d 出堆后 \n", val) - PrintHeap(*h) -} - +// [region]{test_heap} func TestHeap(t *testing.T) { /* 初始化堆 */ // 初始化大顶堆 maxHeap := &intHeap{} heap.Init(maxHeap) /* 元素入堆 */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + // 调用 heap.Interface 的函数,来添加元素 + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) /* 获取堆顶元素 */ top := maxHeap.Top() fmt.Printf("堆顶元素为 %d\n", top) /* 堆顶元素出堆 */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // 调用 heap.Interface 的函数,来移除元素 + fmt.Println(heap.Pop(maxHeap)) // 5 + fmt.Println(heap.Pop(maxHeap)) // 4 + fmt.Println(heap.Pop(maxHeap)) // 3 + fmt.Println(heap.Pop(maxHeap)) // 2 + fmt.Println(heap.Pop(maxHeap)) // 1 /* 获取堆大小 */ size := len(*maxHeap) @@ -59,6 +49,8 @@ func TestHeap(t *testing.T) { fmt.Printf("堆是否为空 %t\n", isEmpty) } +// [endregion]{test_heap} + func TestMyHeap(t *testing.T) { /* 初始化堆 */ // 初始化大顶堆 diff --git a/codes/go/pkg/list_node.go b/codes/go/pkg/list_node.go index 877f8563d..9655c6f5b 100644 --- a/codes/go/pkg/list_node.go +++ b/codes/go/pkg/list_node.go @@ -4,20 +4,23 @@ package pkg +// [region]{list_node} // ListNode 链表节点 type ListNode struct { - Next *ListNode - Val int + Val int // 节点值 + Next *ListNode // 后继节点指针 } // NewListNode 链表节点构造函数 func NewListNode(v int) *ListNode { return &ListNode{ - Next: nil, Val: v, + Next: nil, } } +// [endregion]{list_node} + // ArrayToLinkedList 将数组反序列化为链表 func ArrayToLinkedList(arr []int) *ListNode { // dummy header of linked list diff --git a/codes/java/chapter_heap/heap.java b/codes/java/chapter_heap/heap.java index d18b086b5..817240373 100644 --- a/codes/java/chapter_heap/heap.java +++ b/codes/java/chapter_heap/heap.java @@ -10,56 +10,73 @@ import utils.*; import java.util.*; public class heap { - public static void testPush(Queue heap, int val) { - heap.offer(val); // 元素入堆 - System.out.format("\n元素 %d 入堆后\n", val); - PrintUtil.printHeap(heap); - } - - public static void testPop(Queue heap) { - int val = heap.poll(); // 堆顶元素出堆 - System.out.format("\n堆顶元素 %d 出堆后\n", val); - PrintUtil.printHeap(heap); - } - public static void main(String[] args) { + // [region]{init} /* 初始化堆 */ // 初始化小顶堆 Queue minHeap = new PriorityQueue<>(); // 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可) Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + // [endregion]{init} System.out.println("\n以下测试样例为大顶堆"); + // [region]{push} /* 元素入堆 */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.offer(1); + maxHeap.offer(3); + maxHeap.offer(2); + maxHeap.offer(5); + maxHeap.offer(4); + // [endregion]{push} + PrintUtil.printHeap(maxHeap); + // [region]{peek} /* 获取堆顶元素 */ - int peek = maxHeap.peek(); + int peek = maxHeap.peek(); // 5 + // [endregion]{peek} System.out.format("\n堆顶元素为 %d\n", peek); + // [region]{pop_1} /* 堆顶元素出堆 */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // 出堆元素会形成一个从大到小的序列 + peek = maxHeap.poll(); // 5 + // [endregion]{pop_1} + System.out.println(peek); + // [region]{pop_2} + peek = maxHeap.poll(); // 4 + // [endregion]{pop_2} + System.out.println(peek); + // [region]{pop_3} + peek = maxHeap.poll(); // 3 + // [endregion]{pop_3} + System.out.println(peek); + // [region]{pop_4} + peek = maxHeap.poll(); // 2 + // [endregion]{pop_4} + System.out.println(peek); + // [region]{pop_5} + peek = maxHeap.poll(); // 1 + // [endregion]{pop_5} + System.out.println(peek); + // [region]{size} /* 获取堆大小 */ int size = maxHeap.size(); + // [endregion]{size} System.out.format("\n堆元素数量为 %d\n", size); + // [region]{is_empty} /* 判断堆是否为空 */ boolean isEmpty = maxHeap.isEmpty(); + // [endregion]{is_empty} System.out.format("\n堆是否为空 %b\n", isEmpty); + // [region]{heapify} /* 输入列表并建堆 */ // 时间复杂度为 O(n) ,而非 O(nlogn) minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); + // [endregion]{heapify} System.out.println("\n输入列表并建立小顶堆后"); PrintUtil.printHeap(minHeap); } diff --git a/codes/java/chapter_stack_and_queue/linkedlist_deque.java b/codes/java/chapter_stack_and_queue/linkedlist_deque.java index 37bdaa036..5849572dc 100644 --- a/codes/java/chapter_stack_and_queue/linkedlist_deque.java +++ b/codes/java/chapter_stack_and_queue/linkedlist_deque.java @@ -8,9 +8,10 @@ package chapter_stack_and_queue; import java.util.*; +// [region]{doubly_list_node} /* 双向链表节点 */ class ListNode { - int val; // 节点值 + int val; // 节点值 ListNode next; // 后继节点引用 ListNode prev; // 前驱节点引用 @@ -19,6 +20,7 @@ class ListNode { prev = next = null; } } +// [endregion]{doubly_list_node} /* 基于双向链表实现的双向队列 */ class LinkedListDeque { diff --git a/codes/java/utils/ListNode.java b/codes/java/utils/ListNode.java index 8e1d4d127..c0bde25c1 100755 --- a/codes/java/utils/ListNode.java +++ b/codes/java/utils/ListNode.java @@ -6,14 +6,16 @@ package utils; +// [region]{list_node} /* 链表节点 */ public class ListNode { - public int val; - public ListNode next; + public int val; // 节点值 + public ListNode next; // 指向下一节点的引用 public ListNode(int x) { val = x; } +// [endregion]{list_node} /* 将列表反序列化为链表 */ public static ListNode arrToLinkedList(int[] arr) { @@ -25,4 +27,6 @@ public class ListNode { } return dum.next; } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js b/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js index 37af91b07..352eca1d2 100644 --- a/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js +++ b/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js @@ -4,6 +4,7 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* 双向链表节点 */ class ListNode { prev; // 前驱节点引用 (指针) @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* 基于双向链表实现的双向队列 */ class LinkedListDeque { diff --git a/codes/javascript/modules/ListNode.js b/codes/javascript/modules/ListNode.js index 5a7cd0c22..2f885ae2e 100755 --- a/codes/javascript/modules/ListNode.js +++ b/codes/javascript/modules/ListNode.js @@ -4,6 +4,7 @@ * Author: IsChristina (christinaxia77@foxmail.com) */ +// [region]{list_node} /* 链表节点 */ class ListNode { val; // 节点值 @@ -13,6 +14,7 @@ class ListNode { this.next = next === undefined ? null : next; } } +// [endregion]{list_node} /* 将列表反序列化为链表 */ function arrToLinkedList(arr) { diff --git a/codes/kotlin/chapter_heap/heap.kt b/codes/kotlin/chapter_heap/heap.kt index 5b6dc3a11..56ec82c34 100644 --- a/codes/kotlin/chapter_heap/heap.kt +++ b/codes/kotlin/chapter_heap/heap.kt @@ -9,58 +9,74 @@ package chapter_heap import utils.printHeap import java.util.* -fun testPush(heap: Queue, _val: Int) { - heap.offer(_val) // 元素入堆 - print("\n元素 $_val 入堆后\n") - printHeap(heap) -} - -fun testPop(heap: Queue) { - val _val = heap.poll() // 堆顶元素出堆 - print("\n堆顶元素 $_val 出堆后\n") - printHeap(heap) -} - /* Driver Code */ fun main() { + // [region]{init} /* 初始化堆 */ // 初始化小顶堆 var minHeap = PriorityQueue() - // 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可) val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + // [endregion]{init} println("\n以下测试样例为大顶堆") + // [region]{push} /* 元素入堆 */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + maxHeap.offer(1) + maxHeap.offer(3) + maxHeap.offer(2) + maxHeap.offer(5) + maxHeap.offer(4) + // [endregion]{push} + printHeap(maxHeap) + // [region]{peek} /* 获取堆顶元素 */ - val peek = maxHeap.peek() + var peek = maxHeap.peek() // 5 + // [endregion]{peek} print("\n堆顶元素为 $peek\n") + // [region]{pop_1} /* 堆顶元素出堆 */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // 出堆元素会形成一个从大到小的序列 + peek = maxHeap.poll() // 5 + // [endregion]{pop_1} + println(peek) + // [region]{pop_2} + peek = maxHeap.poll() // 4 + // [endregion]{pop_2} + println(peek) + // [region]{pop_3} + peek = maxHeap.poll() // 3 + // [endregion]{pop_3} + println(peek) + // [region]{pop_4} + peek = maxHeap.poll() // 2 + // [endregion]{pop_4} + println(peek) + // [region]{pop_5} + peek = maxHeap.poll() // 1 + // [endregion]{pop_5} + println(peek) + // [region]{size} /* 获取堆大小 */ val size = maxHeap.size + // [endregion]{size} print("\n堆元素数量为 $size\n") + // [region]{is_empty} /* 判断堆是否为空 */ val isEmpty = maxHeap.isEmpty() + // [endregion]{is_empty} print("\n堆是否为空 $isEmpty\n") + // [region]{heapify} /* 输入列表并建堆 */ // 时间复杂度为 O(n) ,而非 O(nlogn) minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) + // [endregion]{heapify} println("\n输入列表并建立小顶堆后") printHeap(minHeap) } \ No newline at end of file diff --git a/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt b/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt index c18c60570..50277c433 100644 --- a/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt +++ b/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt @@ -6,12 +6,14 @@ package chapter_stack_and_queue +// [region]{doubly_list_node} /* 双向链表节点 */ class ListNode(var _val: Int) { // 节点值 var next: ListNode? = null // 后继节点引用 var prev: ListNode? = null // 前驱节点引用 } +// [endregion]{doubly_list_node} /* 基于双向链表实现的双向队列 */ class LinkedListDeque { @@ -162,4 +164,4 @@ fun main() { /* 判断双向队列是否为空 */ val isEmpty = deque.isEmpty() println("双向队列是否为空 = $isEmpty") -} \ No newline at end of file +} diff --git a/codes/kotlin/utils/ListNode.kt b/codes/kotlin/utils/ListNode.kt index 2fad5f77d..5bebf7182 100644 --- a/codes/kotlin/utils/ListNode.kt +++ b/codes/kotlin/utils/ListNode.kt @@ -6,9 +6,11 @@ package utils +// [region]{list_node} /* 链表节点 */ class ListNode(var _val: Int) { - var next: ListNode? = null + var next: ListNode? = null // 指向下一节点的引用 +// [endregion]{list_node} companion object { /* 将列表反序列化为链表 */ @@ -22,4 +24,6 @@ class ListNode(var _val: Int) { return dum.next } } -} \ No newline at end of file +// [region]{list_node_end} +} +// [endregion]{list_node_end} diff --git a/codes/python/chapter_heap/heap.py b/codes/python/chapter_heap/heap.py index fb73a282a..c38549041 100644 --- a/codes/python/chapter_heap/heap.py +++ b/codes/python/chapter_heap/heap.py @@ -13,59 +13,76 @@ from modules import print_heap import heapq -def test_push(heap: list, val: int, flag: int = 1): - heapq.heappush(heap, flag * val) # 元素入堆 - print(f"\n元素 {val} 入堆后") - print_heap([flag * val for val in heap]) - - -def test_pop(heap: list, flag: int = 1): - val = flag * heapq.heappop(heap) # 堆顶元素出堆 - print(f"\n堆顶元素 {val} 出堆后") - print_heap([flag * val for val in heap]) - - """Driver Code""" if __name__ == "__main__": + # [region]{init} # 初始化小顶堆 min_heap, flag = [], 1 # 初始化大顶堆 max_heap, flag = [], -1 - print("\n以下测试样例为大顶堆") # Python 的 heapq 模块默认实现小顶堆 # 考虑将“元素取负”后再入堆,这样就可以将大小关系颠倒,从而实现大顶堆 # 在本示例中,flag = 1 时对应小顶堆,flag = -1 时对应大顶堆 + # [endregion]{init} + print("\n以下测试样例为大顶堆") + # [region]{push} # 元素入堆 - test_push(max_heap, 1, flag) - test_push(max_heap, 3, flag) - test_push(max_heap, 2, flag) - test_push(max_heap, 5, flag) - test_push(max_heap, 4, flag) + 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) + # [endregion]{push} + print_heap([flag * val for val in max_heap]) + # [region]{peek} # 获取堆顶元素 - peek: int = flag * max_heap[0] + peek: int = flag * max_heap[0] # 5 + # [endregion]{peek} print(f"\n堆顶元素为 {peek}") + # [region]{pop_1} # 堆顶元素出堆 - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) + # 出堆元素会形成一个从大到小的序列 + val = flag * heapq.heappop(max_heap) # 5 + # [endregion]{pop_1} + print(val) + # [region]{pop_2} + val = flag * heapq.heappop(max_heap) # 4 + # [endregion]{pop_2} + print(val) + # [region]{pop_3} + val = flag * heapq.heappop(max_heap) # 3 + # [endregion]{pop_3} + print(val) + # [region]{pop_4} + val = flag * heapq.heappop(max_heap) # 2 + # [endregion]{pop_4} + print(val) + # [region]{pop_5} + val = flag * heapq.heappop(max_heap) # 1 + # [endregion]{pop_5} + print(val) + # [region]{size} # 获取堆大小 size: int = len(max_heap) + # [endregion]{size} print(f"\n堆元素数量为 {size}") + # [region]{is_empty} # 判断堆是否为空 is_empty: bool = not max_heap + # [endregion]{is_empty} print(f"\n堆是否为空 {is_empty}") + # [region]{heapify} # 输入列表并建堆 # 时间复杂度为 O(n) ,而非 O(nlogn) - min_heap = [1, 3, 2, 5, 4] + min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) + # [endregion]{heapify} print("\n输入列表并建立小顶堆后") print_heap(min_heap) diff --git a/codes/python/chapter_stack_and_queue/linkedlist_deque.py b/codes/python/chapter_stack_and_queue/linkedlist_deque.py index 981eceb96..253d558c1 100644 --- a/codes/python/chapter_stack_and_queue/linkedlist_deque.py +++ b/codes/python/chapter_stack_and_queue/linkedlist_deque.py @@ -5,14 +5,16 @@ Author: krahets (krahets@163.com) """ +# [region]{doubly_list_node} 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 # 前驱节点引用 +# [endregion]{doubly_list_node} class LinkedListDeque: diff --git a/codes/python/modules/list_node.py b/codes/python/modules/list_node.py index ee51f234b..4be48f6eb 100644 --- a/codes/python/modules/list_node.py +++ b/codes/python/modules/list_node.py @@ -5,12 +5,14 @@ Author: krahets (krahets@163.com) """ +# [region]{list_node} class ListNode: """链表节点类""" def __init__(self, val: int): self.val: int = val # 节点值 - self.next: ListNode | None = None # 后继节点引用 + self.next: ListNode | None = None # 指向下一节点的引用 +# [endregion]{list_node} def list_to_linked_list(arr: list[int]) -> ListNode | None: diff --git a/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb b/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb index a138827eb..7903b12f3 100644 --- a/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,17 +4,19 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{doubly_list_node} ### 双向链表节点 class ListNode - attr_accessor :val + attr_accessor :val # 节点值 attr_accessor :next # 后继节点引用 - attr_accessor :prev # 前躯节点引用 + attr_accessor :prev # 前驱节点引用 ### 构造方法 ### def initialize(val) @val = val end end +# [endregion]{doubly_list_node} ### 基于双向链表实现的双向队列 ### class LinkedListDeque diff --git a/codes/ruby/utils/list_node.rb b/codes/ruby/utils/list_node.rb index 278a81d28..cca557d4a 100644 --- a/codes/ruby/utils/list_node.rb +++ b/codes/ruby/utils/list_node.rb @@ -4,6 +4,7 @@ Created Time: 2024-03-18 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{list_node} ### 链表节点类 ### class ListNode attr_accessor :val # 节点值 @@ -14,6 +15,7 @@ class ListNode @next = next_node end end +# [endregion]{list_node} ### 将列表反序列化为链表 ### def arr_to_linked_list(arr) diff --git a/codes/rust/chapter_heap/heap.rs b/codes/rust/chapter_heap/heap.rs index 7281865a4..00f8bc01d 100644 --- a/codes/rust/chapter_heap/heap.rs +++ b/codes/rust/chapter_heap/heap.rs @@ -6,22 +6,13 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::{cmp::Reverse, collections::BinaryHeap}; - -fn test_push_max(heap: &mut BinaryHeap, val: i32) { - heap.push(val); // 元素入堆 - println!("\n元素 {} 入堆后", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} - -fn test_pop_max(heap: &mut BinaryHeap) { - let val = heap.pop().unwrap(); - println!("\n堆顶元素 {} 出堆后", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} +// [endregion]{import} /* Driver Code */ fn main() { + // [region]{init} /* 初始化堆 */ // 初始化小顶堆 #[allow(unused_assignments)] @@ -29,43 +20,66 @@ fn main() { // Rust 的 BinaryHeap 是大顶堆,小顶堆一般会“套上”Reverse // 初始化大顶堆 let mut max_heap = BinaryHeap::new(); + // [endregion]{init} println!("\n以下测试样例为大顶堆"); + // [region]{push} /* 元素入堆 */ - test_push_max(&mut max_heap, 1); - test_push_max(&mut max_heap, 3); - test_push_max(&mut max_heap, 2); - test_push_max(&mut max_heap, 5); - test_push_max(&mut max_heap, 4); + max_heap.push(1); + max_heap.push(3); + max_heap.push(2); + max_heap.push(5); + max_heap.push(4); + // [endregion]{push} + print_util::print_heap(max_heap.iter().map(|&val| val).collect()); + // [region]{peek} /* 获取堆顶元素 */ - let peek = max_heap.peek().unwrap(); + let peek = max_heap.peek().unwrap(); // 5 + // [endregion]{peek} println!("\n堆顶元素为 {}", peek); + // [region]{pop_1} /* 堆顶元素出堆 */ - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); + // 出堆元素会形成一个从大到小的序列 + let peek = max_heap.pop().unwrap(); // 5 + // [endregion]{pop_1} + println!("{}", peek); + // [region]{pop_2} + let peek = max_heap.pop().unwrap(); // 4 + // [endregion]{pop_2} + println!("{}", peek); + // [region]{pop_3} + let peek = max_heap.pop().unwrap(); // 3 + // [endregion]{pop_3} + println!("{}", peek); + // [region]{pop_4} + let peek = max_heap.pop().unwrap(); // 2 + // [endregion]{pop_4} + println!("{}", peek); + // [region]{pop_5} + let peek = max_heap.pop().unwrap(); // 1 + // [endregion]{pop_5} + println!("{}", peek); + // [region]{size} /* 获取堆大小 */ let size = max_heap.len(); + // [endregion]{size} println!("\n堆元素数量为 {}", size); + // [region]{is_empty} /* 判断堆是否为空 */ let is_empty = max_heap.is_empty(); + // [endregion]{is_empty} println!("\n堆是否为空 {}", is_empty); + // [region]{heapify} /* 输入列表并建堆 */ // 时间复杂度为 O(n) ,而非 O(nlogn) - min_heap = BinaryHeap::from( - vec![1, 3, 2, 5, 4] - .into_iter() - .map(|val| Reverse(val)) - .collect::>>(), - ); + min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); + // [endregion]{heapify} println!("\n输入列表并建立小顶堆后"); print_util::print_heap(min_heap.iter().map(|&val| val.0).collect()); } diff --git a/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs b/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs index 44eacf4d0..93c8e72d5 100644 --- a/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs +++ b/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs @@ -6,9 +6,12 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::cell::RefCell; use std::rc::Rc; +// [endregion]{import} +// [region]{doubly_list_node} /* 双向链表节点 */ pub struct ListNode { pub val: T, // 节点值 @@ -25,6 +28,7 @@ impl ListNode { })) } } +// [endregion]{doubly_list_node} /* 基于双向链表实现的双向队列 */ #[allow(dead_code)] diff --git a/codes/rust/src/include/list_node.rs b/codes/rust/src/include/list_node.rs index 003ab2989..8f3764aab 100644 --- a/codes/rust/src/include/list_node.rs +++ b/codes/rust/src/include/list_node.rs @@ -4,20 +4,26 @@ * Author: codingonion (coderonion@gmail.com), rongyi (hiarongyi@gmail.com) */ +// [region]{import_cell} use std::cell::RefCell; +// [endregion]{import_cell} use std::collections::HashMap; +// [region]{import_rc} use std::rc::Rc; +// [endregion]{import_rc} +// [region]{list_node} #[derive(Debug)] pub struct ListNode { - pub val: T, - pub next: Option>>>, + pub val: T, // 节点值 + pub next: Option>>>, // 后继节点指针 } impl ListNode { pub fn new(val: T) -> Rc>> { Rc::new(RefCell::new(ListNode { val, next: None })) } +// [endregion]{list_node} /* 将数组反序列化为链表 */ pub fn arr_to_linked_list(array: &[T]) -> Option>>> @@ -54,4 +60,6 @@ impl ListNode { hashmap } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/codes/snippets/chapter_array_and_linkedlist/linked_list.md b/codes/snippets/chapter_array_and_linkedlist/linked_list.md index 1b6bd2e94..e48b849e9 100644 --- a/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -1,52 +1,24 @@ ```python title="" -class ListNode: - """链表节点类""" - def __init__(self, val: int): - self.val: int = val # 节点值 - self.next: ListNode | None = None # 指向下一节点的引用 +[file]{modules/list_node}-[region]{list_node} ``` ```cpp title="" -/* 链表节点结构体 */ -struct ListNode { - int val; // 节点值 - ListNode *next; // 指向下一节点的指针 - ListNode(int x) : val(x), next(nullptr) {} // 构造函数 -}; +[file]{utils/list_node.hpp}-[region]{list_node} ``` ```java title="" -/* 链表节点类 */ -class ListNode { - int val; // 节点值 - ListNode next; // 指向下一节点的引用 - ListNode(int x) { val = x; } // 构造函数 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```csharp title="" -/* 链表节点类 */ -class ListNode(int x) { //构造函数 - public int val = x; // 节点值 - public ListNode? next; // 指向下一节点的引用 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```go title="" -/* 链表节点结构体 */ -type ListNode struct { - Val int // 节点值 - Next *ListNode // 指向下一节点的指针 -} - -// NewListNode 构造函数,创建一个新的链表 -func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } -} +[file]{pkg/list_node}-[region]{list_node} ``` ```swift title="" @@ -62,84 +34,36 @@ class ListNode { ``` ```javascript title="" -/* 链表节点类 */ -class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // 节点值 - this.next = (next === undefined ? null : next); // 指向下一节点的引用 - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```typescript title="" -/* 链表节点类 */ -class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 节点值 - this.next = next === undefined ? null : next; // 指向下一节点的引用 - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```dart title="" -/* 链表节点类 */ -class ListNode { - int val; // 节点值 - ListNode? next; // 指向下一节点的引用 - ListNode(this.val, [this.next]); // 构造函数 -} +[file]{utils/list_node}-[region]{list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; -/* 链表节点类 */ -#[derive(Debug)] -struct ListNode { - val: i32, // 节点值 - next: Option>>, // 指向下一节点的指针 -} +[file]{src/include/list_node}-[region]{import_cell} +[file]{src/include/list_node}-[region]{import_rc} + +[file]{src/include/list_node}-[region]{list_node} +[file]{src/include/list_node}-[region]{list_node_end} ``` ```c title="" -/* 链表节点结构体 */ -typedef struct ListNode { - int val; // 节点值 - struct ListNode *next; // 指向下一节点的指针 -} ListNode; - -/* 构造函数 */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; -} +[file]{utils/list_node.h}-[region]{list_node} ``` ```kotlin title="" -/* 链表节点类 */ -// 构造方法 -class ListNode(x: Int) { - val _val: Int = x // 节点值 - var next: ListNode? = null // 指向下一个节点的引用 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```ruby title="" -# 链表节点类 -class ListNode - attr_accessor :val # 节点值 - attr_accessor :next # 指向下一节点的引用 - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end -end +[file]{utils/list_node}-[region]{list_node} ``` @@ -200,41 +124,19 @@ 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 # 指向前驱节点的引用 +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```cpp title="" -/* 双向链表节点结构体 */ -struct ListNode { - int val; // 节点值 - ListNode *next; // 指向后继节点的指针 - ListNode *prev; // 指向前驱节点的指针 - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 构造函数 -}; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```java title="" -/* 双向链表节点类 */ -class ListNode { - int val; // 节点值 - ListNode next; // 指向后继节点的引用 - ListNode prev; // 指向前驱节点的引用 - ListNode(int x) { val = x; } // 构造函数 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```csharp title="" -/* 双向链表节点类 */ -class ListNode(int x) { // 构造函数 - public int val = x; // 节点值 - public ListNode? next; // 指向后继节点的引用 - public ListNode? prev; // 指向前驱节点的引用 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```go title="" @@ -256,117 +158,35 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* 双向链表节点类 */ -class ListNode { - var val: Int // 节点值 - var next: ListNode? // 指向后继节点的引用 - var prev: ListNode? // 指向前驱节点的引用 - - init(x: Int) { // 构造函数 - val = x - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // 指向前驱节点的引用 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // 指向前驱节点的引用 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```dart title="" -/* 双向链表节点类 */ -class ListNode { - int val; // 节点值 - ListNode? next; // 指向后继节点的引用 - ListNode? prev; // 指向前驱节点的引用 - ListNode(this.val, [this.next, this.prev]); // 构造函数 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{import} -/* 双向链表节点类型 */ -#[derive(Debug)] -struct ListNode { - val: i32, // 节点值 - next: Option>>, // 指向后继节点的指针 - prev: Option>>, // 指向前驱节点的指针 -} - -/* 构造函数 */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```c title="" -/* 双向链表节点结构体 */ -typedef struct ListNode { - int val; // 节点值 - struct ListNode *next; // 指向后继节点的指针 - struct ListNode *prev; // 指向前驱节点的指针 -} ListNode; - -/* 构造函数 */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```kotlin title="" -/* 双向链表节点类 */ -// 构造方法 -class ListNode(x: Int) { - val _val: Int = x // 节点值 - var next: ListNode? = null // 指向后继节点的引用 - var prev: ListNode? = null // 指向前驱节点的引用 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```ruby title="" -# 双向链表节点类 -class ListNode - attr_accessor :val # 节点值 - attr_accessor :next # 指向后继节点的引用 - attr_accessor :prev # 指向前驱节点的引用 - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end -end +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` diff --git a/codes/snippets/chapter_heap/heap.md b/codes/snippets/chapter_heap/heap.md index e02b5332e..6146cc148 100644 --- a/codes/snippets/chapter_heap/heap.md +++ b/codes/snippets/chapter_heap/heap.md @@ -1,256 +1,110 @@ ```python title="heap.py" -# 初始化小顶堆 -min_heap, flag = [], 1 -# 初始化大顶堆 -max_heap, flag = [], -1 +[file]{heap}-[region]{init} -# Python 的 heapq 模块默认实现小顶堆 -# 考虑将“元素取负”后再入堆,这样就可以将大小关系颠倒,从而实现大顶堆 -# 在本示例中,flag = 1 时对应小顶堆,flag = -1 时对应大顶堆 +[file]{heap}-[region]{push} -# 元素入堆 -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) +[file]{heap}-[region]{peek} -# 获取堆顶元素 -peek: int = flag * max_heap[0] # 5 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_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 +[file]{heap}-[region]{size} -# 获取堆大小 -size: int = len(max_heap) +[file]{heap}-[region]{is_empty} -# 判断堆是否为空 -is_empty: bool = not max_heap - -# 输入列表并建堆 -min_heap: list[int] = [1, 3, 2, 5, 4] -heapq.heapify(min_heap) +[file]{heap}-[region]{heapify} ``` ```cpp title="heap.cpp" -/* 初始化堆 */ -// 初始化小顶堆 -priority_queue, greater> minHeap; -// 初始化大顶堆 -priority_queue, less> maxHeap; +[file]{heap}-[region]{init} -/* 元素入堆 */ -maxHeap.push(1); -maxHeap.push(3); -maxHeap.push(2); -maxHeap.push(5); -maxHeap.push(4); +[file]{heap}-[region]{push} -/* 获取堆顶元素 */ -int peek = maxHeap.top(); // 5 +[file]{heap}-[region]{peek} -/* 堆顶元素出堆 */ -// 出堆元素会形成一个从大到小的序列 -maxHeap.pop(); // 5 -maxHeap.pop(); // 4 -maxHeap.pop(); // 3 -maxHeap.pop(); // 2 -maxHeap.pop(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 获取堆大小 */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* 判断堆是否为空 */ -bool isEmpty = maxHeap.empty(); +[file]{heap}-[region]{is_empty} -/* 输入列表并建堆 */ -vector input{1, 3, 2, 5, 4}; -minHeap = priority_queue, greater>(input.begin(), input.end()); +[file]{heap}-[region]{heapify} ``` ```java title="heap.java" -/* 初始化堆 */ -// 初始化小顶堆 -Queue minHeap = new PriorityQueue<>(); -// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可) -Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); +[file]{heap}-[region]{init} -/* 元素入堆 */ -maxHeap.offer(1); -maxHeap.offer(3); -maxHeap.offer(2); -maxHeap.offer(5); -maxHeap.offer(4); +[file]{heap}-[region]{push} -/* 获取堆顶元素 */ -int peek = maxHeap.peek(); // 5 +[file]{heap}-[region]{peek} -/* 堆顶元素出堆 */ -// 出堆元素会形成一个从大到小的序列 -peek = maxHeap.poll(); // 5 -peek = maxHeap.poll(); // 4 -peek = maxHeap.poll(); // 3 -peek = maxHeap.poll(); // 2 -peek = maxHeap.poll(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 获取堆大小 */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* 判断堆是否为空 */ -boolean isEmpty = maxHeap.isEmpty(); +[file]{heap}-[region]{is_empty} -/* 输入列表并建堆 */ -minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +[file]{heap}-[region]{heapify} ``` ```csharp title="heap.cs" -/* 初始化堆 */ -// 初始化小顶堆 -PriorityQueue minHeap = new(); -// 初始化大顶堆(使用 lambda 表达式修改 Comparer 即可) -PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); +[file]{heap}-[region]{init} -/* 元素入堆 */ -maxHeap.Enqueue(1, 1); -maxHeap.Enqueue(3, 3); -maxHeap.Enqueue(2, 2); -maxHeap.Enqueue(5, 5); -maxHeap.Enqueue(4, 4); +[file]{heap}-[region]{push} -/* 获取堆顶元素 */ -int peek = maxHeap.Peek();//5 +[file]{heap}-[region]{peek} -/* 堆顶元素出堆 */ -// 出堆元素会形成一个从大到小的序列 -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 获取堆大小 */ -int size = maxHeap.Count; +[file]{heap}-[region]{size} -/* 判断堆是否为空 */ -bool isEmpty = maxHeap.Count == 0; +[file]{heap}-[region]{is_empty} -/* 输入列表并建堆 */ -minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +[file]{heap}-[region]{heapify} ``` ```go title="heap.go" -// Go 语言中可以通过实现 heap.Interface 来构建整数大顶堆 -// 实现 heap.Interface 需要同时实现 sort.Interface -type intHeap []any +[file]{heap}-[region]{int_heap} -// Push heap.Interface 的方法,实现推入元素到堆 -func (h *intHeap) Push(x any) { - // Push 和 Pop 使用 pointer receiver 作为参数 - // 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。 - *h = append(*h, x.(int)) -} - -// Pop heap.Interface 的方法,实现弹出堆顶元素 -func (h *intHeap) Pop() any { - // 待出堆元素存放在最后 - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last -} - -// Len sort.Interface 的方法 -func (h *intHeap) Len() int { - return len(*h) -} - -// Less sort.Interface 的方法 -func (h *intHeap) Less(i, j int) bool { - // 如果实现小顶堆,则需要调整为小于号 - return (*h)[i].(int) > (*h)[j].(int) -} - -// Swap sort.Interface 的方法 -func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] -} - -// Top 获取堆顶元素 -func (h *intHeap) Top() any { - return (*h)[0] -} - -/* Driver Code */ -func TestHeap(t *testing.T) { - /* 初始化堆 */ - // 初始化大顶堆 - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* 元素入堆 */ - // 调用 heap.Interface 的方法,来添加元素 - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* 获取堆顶元素 */ - 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 - - /* 获取堆大小 */ - size := len(*maxHeap) - fmt.Printf("堆元素数量为 %d\n", size) - - /* 判断堆是否为空 */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("堆是否为空 %t\n", isEmpty) -} +[file]{heap_test}-[region]{test_heap} ``` ```swift title="heap.swift" -/* 初始化堆 */ -// Swift 的 Heap 类型同时支持最大堆和最小堆,且需要引入 swift-collections -var heap = Heap() +[file]{heap}-[region]{import} -/* 元素入堆 */ -heap.insert(1) -heap.insert(3) -heap.insert(2) -heap.insert(5) -heap.insert(4) +[file]{heap}-[region]{init} -/* 获取堆顶元素 */ -var peek = heap.max()! +[file]{heap}-[region]{push} -/* 堆顶元素出堆 */ -peek = heap.removeMax() // 5 -peek = heap.removeMax() // 4 -peek = heap.removeMax() // 3 -peek = heap.removeMax() // 2 -peek = heap.removeMax() // 1 +[file]{heap}-[region]{peek} -/* 获取堆大小 */ -let size = heap.count +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 判断堆是否为空 */ -let isEmpty = heap.isEmpty +[file]{heap}-[region]{size} -/* 输入列表并建堆 */ -let heap2 = Heap([1, 3, 2, 5, 4]) +[file]{heap}-[region]{is_empty} + +[file]{heap}-[region]{heapify} ``` ```javascript title="heap.js" @@ -266,41 +120,25 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +[file]{heap}-[region]{import} -/* 初始化堆 */ -// 初始化小顶堆 -let mut min_heap = BinaryHeap::>::new(); -// 初始化大顶堆 -let mut max_heap = BinaryHeap::new(); +[file]{heap}-[region]{init} -/* 元素入堆 */ -max_heap.push(1); -max_heap.push(3); -max_heap.push(2); -max_heap.push(5); -max_heap.push(4); +[file]{heap}-[region]{push} -/* 获取堆顶元素 */ -let peek = max_heap.peek().unwrap(); // 5 +[file]{heap}-[region]{peek} -/* 堆顶元素出堆 */ -// 出堆元素会形成一个从大到小的序列 -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 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 获取堆大小 */ -let size = max_heap.len(); +[file]{heap}-[region]{size} -/* 判断堆是否为空 */ -let is_empty = max_heap.is_empty(); +[file]{heap}-[region]{is_empty} -/* 输入列表并建堆 */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +[file]{heap}-[region]{heapify} ``` ```c title="heap.c" @@ -308,38 +146,23 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse ``` ```kotlin title="heap.kt" -/* 初始化堆 */ -// 初始化小顶堆 -var minHeap = PriorityQueue() -// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可) -val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } +[file]{heap}-[region]{init} -/* 元素入堆 */ -maxHeap.offer(1) -maxHeap.offer(3) -maxHeap.offer(2) -maxHeap.offer(5) -maxHeap.offer(4) +[file]{heap}-[region]{push} -/* 获取堆顶元素 */ -var peek = maxHeap.peek() // 5 +[file]{heap}-[region]{peek} -/* 堆顶元素出堆 */ -// 出堆元素会形成一个从大到小的序列 -peek = maxHeap.poll() // 5 -peek = maxHeap.poll() // 4 -peek = maxHeap.poll() // 3 -peek = maxHeap.poll() // 2 -peek = maxHeap.poll() // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 获取堆大小 */ -val size = maxHeap.size +[file]{heap}-[region]{size} -/* 判断堆是否为空 */ -val isEmpty = maxHeap.isEmpty() +[file]{heap}-[region]{is_empty} -/* 输入列表并建堆 */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +[file]{heap}-[region]{heapify} ``` ```ruby title="heap.rb" diff --git a/codes/swift/chapter_heap/heap.swift b/codes/swift/chapter_heap/heap.swift index fc85880a0..8b777bb53 100644 --- a/codes/swift/chapter_heap/heap.swift +++ b/codes/swift/chapter_heap/heap.swift @@ -4,58 +4,76 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{import} import HeapModule +// [endregion]{import} import utils -func testPush(heap: inout Heap, val: Int) { - heap.insert(val) - print("\n元素 \(val) 入堆后\n") - PrintUtil.printHeap(queue: heap.unordered) -} - -func testPop(heap: inout Heap) { - let val = heap.removeMax() - print("\n堆顶元素 \(val) 出堆后\n") - PrintUtil.printHeap(queue: heap.unordered) -} - @main enum _Heap { /* Driver Code */ static func main() { + // [region]{init} /* 初始化堆 */ // Swift 的 Heap 类型同时支持最大堆和最小堆 var heap = Heap() + // [endregion]{init} + // [region]{push} /* 元素入堆 */ - testPush(heap: &heap, val: 1) - testPush(heap: &heap, val: 3) - testPush(heap: &heap, val: 2) - testPush(heap: &heap, val: 5) - testPush(heap: &heap, val: 4) + heap.insert(1) + heap.insert(3) + heap.insert(2) + heap.insert(5) + heap.insert(4) + // [endregion]{push} + PrintUtil.printHeap(queue: heap.unordered) + // [region]{peek} /* 获取堆顶元素 */ - let peek = heap.max() + var peek = heap.max() + // [endregion]{peek} print("\n堆顶元素为 \(peek!)\n") + // [region]{pop_1} /* 堆顶元素出堆 */ - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) + peek = heap.removeMax() // 5 + // [endregion]{pop_1} + print(peek!) + // [region]{pop_2} + peek = heap.removeMax() // 4 + // [endregion]{pop_2} + print(peek!) + // [region]{pop_3} + peek = heap.removeMax() // 3 + // [endregion]{pop_3} + print(peek!) + // [region]{pop_4} + peek = heap.removeMax() // 2 + // [endregion]{pop_4} + print(peek!) + // [region]{pop_5} + peek = heap.removeMax() // 1 + // [endregion]{pop_5} + print(peek!) + // [region]{size} /* 获取堆大小 */ let size = heap.count + // [endregion]{size} print("\n堆元素数量为 \(size)\n") + // [region]{is_empty} /* 判断堆是否为空 */ let isEmpty = heap.isEmpty + // [endregion]{is_empty} print("\n堆是否为空 \(isEmpty)\n") + // [region]{heapify} /* 输入列表并建堆 */ // 时间复杂度为 O(n) ,而非 O(nlogn) let heap2 = Heap([1, 3, 2, 5, 4]) + // [endregion]{heapify} print("\n输入列表并建立堆后") PrintUtil.printHeap(queue: heap2.unordered) } diff --git a/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift b/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift index 64a0d2ac5..28ef7b5b5 100644 --- a/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift +++ b/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift @@ -4,6 +4,7 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{doubly_list_node} /* 双向链表节点 */ class ListNode { var val: Int // 节点值 @@ -14,6 +15,7 @@ class ListNode { self.val = val } } +// [endregion]{doubly_list_node} /* 基于双向链表实现的双向队列 */ class LinkedListDeque { diff --git a/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts b/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts index f4ae6ed7c..3a69c10b4 100644 --- a/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -4,10 +4,11 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* 双向链表节点 */ class ListNode { - prev: ListNode; // 前驱节点引用 (指针) - next: ListNode; // 后继节点引用 (指针) + prev: ListNode | null; // 前驱节点引用 (指针) + next: ListNode | null; // 后继节点引用 (指针) val: number; // 节点值 constructor(val: number) { @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* 基于双向链表实现的双向队列 */ class LinkedListDeque { diff --git a/codes/typescript/modules/ListNode.ts b/codes/typescript/modules/ListNode.ts index b42905f58..aab9a63e5 100644 --- a/codes/typescript/modules/ListNode.ts +++ b/codes/typescript/modules/ListNode.ts @@ -4,15 +4,17 @@ * Author: Justin (xiefahit@gmail.com) */ +// [region]{list_node} /* 链表节点 */ 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; } } +// [endregion]{list_node} /* 将数组反序列化为链表 */ function arrToLinkedList(arr: number[]): ListNode | null { diff --git a/en/codes/c/chapter_stack_and_queue/linkedlist_deque.c b/en/codes/c/chapter_stack_and_queue/linkedlist_deque.c index f8b7aff4f..7604b16f8 100644 --- a/en/codes/c/chapter_stack_and_queue/linkedlist_deque.c +++ b/en/codes/c/chapter_stack_and_queue/linkedlist_deque.c @@ -6,6 +6,7 @@ #include "../utils/common.h" +// [region]{doubly_list_node} /* Doubly linked list node */ typedef struct DoublyListNode { int val; // Node value @@ -21,6 +22,7 @@ DoublyListNode *newDoublyListNode(int num) { new->prev = NULL; return new; } +// [endregion]{doubly_list_node} /* Destructor */ void delDoublyListNode(DoublyListNode *node) { diff --git a/en/codes/c/utils/list_node.h b/en/codes/c/utils/list_node.h index 58040602c..9b180851a 100644 --- a/en/codes/c/utils/list_node.h +++ b/en/codes/c/utils/list_node.h @@ -11,6 +11,7 @@ extern "C" { #endif +// [region]{list_node} /* Linked list node structure */ typedef struct ListNode { int val; // Node value @@ -25,6 +26,7 @@ ListNode *newListNode(int val) { node->next = NULL; return node; } +// [endregion]{list_node} /* Deserialize an array into a linked list */ ListNode *arrToLinkedList(const int *arr, size_t size) { diff --git a/en/codes/cpp/chapter_heap/heap.cpp b/en/codes/cpp/chapter_heap/heap.cpp index 9789eb385..df05d9fe4 100644 --- a/en/codes/cpp/chapter_heap/heap.cpp +++ b/en/codes/cpp/chapter_heap/heap.cpp @@ -6,59 +6,75 @@ #include "../utils/common.hpp" -void testPush(priority_queue &heap, int val) { - heap.push(val); // Push an element onto the heap - cout << "\nAfter pushing element " << val << " onto the heap:" << endl; - printHeap(heap); -} - -void testPop(priority_queue &heap) { - int val = heap.top(); - heap.pop(); - cout << "\nAfter popping top element " << val << " from the heap:" << endl; - printHeap(heap); -} - /* Driver code */ int main() { + // [region]{init} /* Initialize the heap */ // Initialize a min heap - // priority_queue, greater> minHeap; + priority_queue, greater> minHeap; // Initialize a max heap priority_queue, less> maxHeap; + // [endregion]{init} cout << "\nThe following example uses a max heap" << endl; + // [region]{push} /* Push an element onto the heap */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.push(1); + maxHeap.push(3); + maxHeap.push(2); + maxHeap.push(5); + maxHeap.push(4); + // [endregion]{push} + printHeap(maxHeap); + // [region]{peek} /* Get the top element of the heap */ - int peek = maxHeap.top(); + int peek = maxHeap.top(); // 5 + // [endregion]{peek} cout << "\nTop element of the heap: " << peek << endl; + // [region]{pop_1} /* Pop the top element from the heap */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // The elements are popped in descending order + maxHeap.pop(); // 5 + // [endregion]{pop_1} + printHeap(maxHeap); + // [region]{pop_2} + maxHeap.pop(); // 4 + // [endregion]{pop_2} + printHeap(maxHeap); + // [region]{pop_3} + maxHeap.pop(); // 3 + // [endregion]{pop_3} + printHeap(maxHeap); + // [region]{pop_4} + maxHeap.pop(); // 2 + // [endregion]{pop_4} + printHeap(maxHeap); + // [region]{pop_5} + maxHeap.pop(); // 1 + // [endregion]{pop_5} + printHeap(maxHeap); + // [region]{size} /* Get the heap size */ int size = maxHeap.size(); + // [endregion]{size} cout << "\nNumber of elements in the heap: " << size << endl; + // [region]{is_empty} /* Check whether the heap is empty */ bool isEmpty = maxHeap.empty(); + // [endregion]{is_empty} cout << "\nIs the heap empty: " << isEmpty << endl; + // [region]{heapify} /* Build a heap from an input list */ // The time complexity is O(n), not O(nlogn) vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); + minHeap = priority_queue, greater>(input.begin(), input.end()); + // [endregion]{heapify} cout << "After building a min heap from the input list:" << endl; printHeap(minHeap); diff --git a/en/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp b/en/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp index b5c8957b2..4f2d2effc 100644 --- a/en/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp +++ b/en/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp @@ -6,6 +6,7 @@ #include "../utils/common.hpp" +// [region]{doubly_list_node} /* Doubly linked list node */ struct DoublyListNode { int val; // Node value @@ -14,6 +15,7 @@ struct DoublyListNode { DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { } }; +// [endregion]{doubly_list_node} /* Deque implemented with a doubly linked list */ class LinkedListDeque { diff --git a/en/codes/cpp/utils/list_node.hpp b/en/codes/cpp/utils/list_node.hpp index 3890e724d..265435f6c 100644 --- a/en/codes/cpp/utils/list_node.hpp +++ b/en/codes/cpp/utils/list_node.hpp @@ -11,13 +11,15 @@ using namespace std; +// [region]{list_node} /* Linked list node */ struct ListNode { - int val; - ListNode *next; + int val; // Node value + ListNode *next; // Pointer to the next node ListNode(int x) : val(x), next(nullptr) { } }; +// [endregion]{list_node} /* Deserialize a list into a linked list */ ListNode *vecToLinkedList(vector list) { diff --git a/en/codes/csharp/chapter_heap/heap.cs b/en/codes/csharp/chapter_heap/heap.cs index 8ad49bd2e..d9a708b49 100644 --- a/en/codes/csharp/chapter_heap/heap.cs +++ b/en/codes/csharp/chapter_heap/heap.cs @@ -7,57 +7,72 @@ namespace hello_algo.chapter_heap; public class heap { - void TestPush(PriorityQueue heap, int val) { - heap.Enqueue(val, val); // Push an element onto the heap - Console.WriteLine($"\nAfter pushing {val} onto the heap:\n"); - PrintUtil.PrintHeap(heap); - } - - void TestPop(PriorityQueue heap) { - int val = heap.Dequeue(); // Pop the top element from the heap - Console.WriteLine($"\nAfter popping the top element {val} from the heap:\n"); - PrintUtil.PrintHeap(heap); - } - [Test] public void Test() { + // [region]{init} /* Initialize heaps */ // Initialize a min heap PriorityQueue minHeap = new(); // Initialize a max heap (use a lambda expression to customize the Comparer) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + // [endregion]{init} Console.WriteLine("The following examples use a max heap"); + // [region]{push} /* Push an element onto the heap */ - TestPush(maxHeap, 1); - TestPush(maxHeap, 3); - TestPush(maxHeap, 2); - TestPush(maxHeap, 5); - TestPush(maxHeap, 4); + maxHeap.Enqueue(1, 1); + maxHeap.Enqueue(3, 3); + maxHeap.Enqueue(2, 2); + maxHeap.Enqueue(5, 5); + maxHeap.Enqueue(4, 4); + // [endregion]{push} + PrintUtil.PrintHeap(maxHeap); + // [region]{peek} /* Get the top element of the heap */ - int peek = maxHeap.Peek(); + int peek = maxHeap.Peek(); // 5 + // [endregion]{peek} Console.WriteLine($"Top element of the heap: {peek}"); + // [region]{pop_1} /* Pop the top element from the heap */ // The elements are popped in descending order - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); + peek = maxHeap.Dequeue(); // 5 + // [endregion]{pop_1} + Console.WriteLine(peek); + // [region]{pop_2} + peek = maxHeap.Dequeue(); // 4 + // [endregion]{pop_2} + Console.WriteLine(peek); + // [region]{pop_3} + peek = maxHeap.Dequeue(); // 3 + // [endregion]{pop_3} + Console.WriteLine(peek); + // [region]{pop_4} + peek = maxHeap.Dequeue(); // 2 + // [endregion]{pop_4} + Console.WriteLine(peek); + // [region]{pop_5} + peek = maxHeap.Dequeue(); // 1 + // [endregion]{pop_5} + Console.WriteLine(peek); + // [region]{size} /* Get the heap size */ int size = maxHeap.Count; + // [endregion]{size} Console.WriteLine($"Number of elements in the heap: {size}"); + // [region]{is_empty} /* Check whether the heap is empty */ bool isEmpty = maxHeap.Count == 0; + // [endregion]{is_empty} Console.WriteLine($"Is the heap empty? {isEmpty}"); + // [region]{heapify} /* Build a heap from an input list */ - var list = new int[] { 1, 3, 2, 5, 4 }; - minHeap = new PriorityQueue(list.Select(x => (x, x))); + minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); + // [endregion]{heapify} Console.WriteLine("After building a min heap from the input list:"); PrintUtil.PrintHeap(minHeap); } diff --git a/en/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs b/en/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs index e919d5bb9..dd41c5d5e 100644 --- a/en/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs +++ b/en/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs @@ -6,12 +6,14 @@ namespace hello_algo.chapter_stack_and_queue; +// [region]{doubly_list_node} /* Doubly linked list node */ public class ListNode(int val) { - public int val = val; // Node value + public int val = val; // Node value public ListNode? next = null; // Reference to the next node public ListNode? prev = null; // Reference to the previous node } +// [endregion]{doubly_list_node} /* Deque implemented with a doubly linked list */ public class LinkedListDeque { diff --git a/en/codes/csharp/utils/ListNode.cs b/en/codes/csharp/utils/ListNode.cs index 6921f8bed..b0c23578d 100644 --- a/en/codes/csharp/utils/ListNode.cs +++ b/en/codes/csharp/utils/ListNode.cs @@ -4,10 +4,12 @@ namespace hello_algo.utils; +// [region]{list_node} /* Linked list node */ public class ListNode(int x) { - public int val = x; - public ListNode? next; + public int val = x; // Node value + public ListNode? next; // Reference to the next node +// [endregion]{list_node} /* Deserialize an array into a linked list */ public static ListNode? ArrToLinkedList(int[] arr) { @@ -29,4 +31,6 @@ public class ListNode(int x) { } return string.Join("->", list); } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/en/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart b/en/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart index 9e1a372e7..be2bd68c1 100644 --- a/en/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart +++ b/en/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart @@ -4,6 +4,7 @@ * Author: liuyuxin (gvenusleo@gmail.com) */ +// [region]{doubly_list_node} /* Doubly linked list node */ class ListNode { int val; // Node value @@ -12,6 +13,7 @@ class ListNode { ListNode(this.val, {this.next, this.prev}); } +// [endregion]{doubly_list_node} /* Deque implemented with a doubly linked list */ class LinkedListDeque { diff --git a/en/codes/dart/utils/list_node.dart b/en/codes/dart/utils/list_node.dart index 96783670b..c86672251 100644 --- a/en/codes/dart/utils/list_node.dart +++ b/en/codes/dart/utils/list_node.dart @@ -4,13 +4,15 @@ * Author: Jefferson (JeffersonHuang77@gmail.com) */ +// [region]{list_node} /* Linked list node */ class ListNode { - int val; - ListNode? next; + int val; // Node value + ListNode? next; // Reference to the next node - ListNode(this.val, [this.next]); + ListNode(this.val, [this.next]); // Constructor } +// [endregion]{list_node} /* Deserialize a list into a linked list */ ListNode? listToLinkedList(List list) { diff --git a/en/codes/go/chapter_heap/heap.go b/en/codes/go/chapter_heap/heap.go index 9d99bc57c..f9d89fac8 100644 --- a/en/codes/go/chapter_heap/heap.go +++ b/en/codes/go/chapter_heap/heap.go @@ -4,6 +4,7 @@ package chapter_heap +// [region]{int_heap} // In Go, implement heap.Interface to build an integer max heap // Implementing heap.Interface also requires implementing sort.Interface type intHeap []any @@ -43,3 +44,5 @@ func (h *intHeap) Swap(i, j int) { func (h *intHeap) Top() any { return (*h)[0] } + +// [endregion]{int_heap} diff --git a/en/codes/go/chapter_heap/heap_test.go b/en/codes/go/chapter_heap/heap_test.go index 07e98634b..ba4128d52 100644 --- a/en/codes/go/chapter_heap/heap_test.go +++ b/en/codes/go/chapter_heap/heap_test.go @@ -13,42 +13,32 @@ import ( . "github.com/krahets/hello-algo/pkg" ) -func testPush(h *intHeap, val int) { - // Call heap.Push, which uses heap.Interface 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 - val := heap.Pop(h) - fmt.Printf("\nAfter popping the top element %d from the heap: \n", val) - PrintHeap(*h) -} - +// [region]{test_heap} func TestHeap(t *testing.T) { /* Initialize the heap */ // Initialize a max heap maxHeap := &intHeap{} heap.Init(maxHeap) /* Push an element onto the heap */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + // Call heap.Push, which uses heap.Interface to add an element + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) /* Get the top element of the heap */ top := maxHeap.Top() fmt.Printf("Top element of the heap: %d\n", top) /* Pop the top element from the heap */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // Call heap.Pop, which uses heap.Interface to remove the top element + fmt.Println(heap.Pop(maxHeap)) // 5 + fmt.Println(heap.Pop(maxHeap)) // 4 + fmt.Println(heap.Pop(maxHeap)) // 3 + fmt.Println(heap.Pop(maxHeap)) // 2 + fmt.Println(heap.Pop(maxHeap)) // 1 /* Get the heap size */ size := len(*maxHeap) @@ -59,6 +49,8 @@ func TestHeap(t *testing.T) { fmt.Printf("Is the heap empty? %t\n", isEmpty) } +// [endregion]{test_heap} + func TestMyHeap(t *testing.T) { /* Initialize the heap */ // Initialize a max heap diff --git a/en/codes/go/pkg/list_node.go b/en/codes/go/pkg/list_node.go index 687dd9144..0c3675b21 100644 --- a/en/codes/go/pkg/list_node.go +++ b/en/codes/go/pkg/list_node.go @@ -4,20 +4,23 @@ package pkg +// [region]{list_node} // ListNode represents a linked list node. type ListNode struct { - Next *ListNode - Val int + Val int // Node value + Next *ListNode // Pointer to the next node } // NewListNode constructs a linked list node. func NewListNode(v int) *ListNode { return &ListNode{ - Next: nil, Val: v, + Next: nil, } } +// [endregion]{list_node} + // ArrayToLinkedList deserializes an array into a linked list. func ArrayToLinkedList(arr []int) *ListNode { // Dummy head of the linked list diff --git a/en/codes/java/chapter_heap/heap.java b/en/codes/java/chapter_heap/heap.java index c7ae37863..43153f16f 100644 --- a/en/codes/java/chapter_heap/heap.java +++ b/en/codes/java/chapter_heap/heap.java @@ -10,56 +10,73 @@ import utils.*; import java.util.*; public class heap { - public static void testPush(Queue heap, int val) { - heap.offer(val); // Push an element onto the heap - System.out.format("\nAfter pushing %d onto the heap:\n", val); - PrintUtil.printHeap(heap); - } - - public static void testPop(Queue heap) { - int val = heap.poll(); // Pop the top element from the heap - System.out.format("\nAfter popping the top element %d:\n", val); - PrintUtil.printHeap(heap); - } - public static void main(String[] args) { + // [region]{init} /* Initialize heaps */ // Initialize a min heap Queue minHeap = new PriorityQueue<>(); // Initialize a max heap by supplying a lambda expression as the Comparator Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + // [endregion]{init} System.out.println("\nThe following example uses a max heap"); + // [region]{push} /* Push an element onto the heap */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.offer(1); + maxHeap.offer(3); + maxHeap.offer(2); + maxHeap.offer(5); + maxHeap.offer(4); + // [endregion]{push} + PrintUtil.printHeap(maxHeap); + // [region]{peek} /* Get the top element of the heap */ - int peek = maxHeap.peek(); + int peek = maxHeap.peek(); // 5 + // [endregion]{peek} System.out.format("\nTop element: %d\n", peek); + // [region]{pop_1} /* Pop the top element from the heap */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // The elements are popped in descending order + peek = maxHeap.poll(); // 5 + // [endregion]{pop_1} + System.out.println(peek); + // [region]{pop_2} + peek = maxHeap.poll(); // 4 + // [endregion]{pop_2} + System.out.println(peek); + // [region]{pop_3} + peek = maxHeap.poll(); // 3 + // [endregion]{pop_3} + System.out.println(peek); + // [region]{pop_4} + peek = maxHeap.poll(); // 2 + // [endregion]{pop_4} + System.out.println(peek); + // [region]{pop_5} + peek = maxHeap.poll(); // 1 + // [endregion]{pop_5} + System.out.println(peek); + // [region]{size} /* Get the heap size */ int size = maxHeap.size(); + // [endregion]{size} System.out.format("\nNumber of elements in the heap: %d\n", size); + // [region]{is_empty} /* Check whether the heap is empty */ boolean isEmpty = maxHeap.isEmpty(); + // [endregion]{is_empty} System.out.format("\nIs the heap empty? %b\n", isEmpty); + // [region]{heapify} /* 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)); + // [endregion]{heapify} System.out.println("\nAfter building a min heap from the input list:"); PrintUtil.printHeap(minHeap); } diff --git a/en/codes/java/chapter_stack_and_queue/linkedlist_deque.java b/en/codes/java/chapter_stack_and_queue/linkedlist_deque.java index 81aee5115..2d4668ca8 100644 --- a/en/codes/java/chapter_stack_and_queue/linkedlist_deque.java +++ b/en/codes/java/chapter_stack_and_queue/linkedlist_deque.java @@ -8,9 +8,10 @@ package chapter_stack_and_queue; import java.util.*; +// [region]{doubly_list_node} /* Doubly linked list node */ class ListNode { - int val; // Node value + int val; // Node value ListNode next; // Reference to the next node ListNode prev; // Reference to the previous node @@ -19,6 +20,7 @@ class ListNode { prev = next = null; } } +// [endregion]{doubly_list_node} /* Deque implemented with a doubly linked list */ class LinkedListDeque { diff --git a/en/codes/java/utils/ListNode.java b/en/codes/java/utils/ListNode.java index a9bf9b9e6..b3d8ea047 100644 --- a/en/codes/java/utils/ListNode.java +++ b/en/codes/java/utils/ListNode.java @@ -6,14 +6,16 @@ package utils; +// [region]{list_node} /* Linked list node */ public class ListNode { - public int val; - public ListNode next; + public int val; // Node value + public ListNode next; // Reference to the next node public ListNode(int x) { val = x; } +// [endregion]{list_node} /* Deserialize an array into a linked list */ public static ListNode arrToLinkedList(int[] arr) { @@ -25,4 +27,6 @@ public class ListNode { } return dum.next; } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/en/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js b/en/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js index e27864270..593ab00c9 100644 --- a/en/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js +++ b/en/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js @@ -4,6 +4,7 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* Doubly linked list node */ class ListNode { prev; // Reference (pointer) to the previous node @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* Deque implemented with a doubly linked list */ class LinkedListDeque { diff --git a/en/codes/javascript/modules/ListNode.js b/en/codes/javascript/modules/ListNode.js index b2dd1604a..57c404457 100644 --- a/en/codes/javascript/modules/ListNode.js +++ b/en/codes/javascript/modules/ListNode.js @@ -4,6 +4,7 @@ * Author: IsChristina (christinaxia77@foxmail.com) */ +// [region]{list_node} /* Linked list node */ class ListNode { val; // Node value @@ -13,6 +14,7 @@ class ListNode { this.next = next === undefined ? null : next; } } +// [endregion]{list_node} /* Deserialize a list into a linked list */ function arrToLinkedList(arr) { diff --git a/en/codes/kotlin/chapter_heap/heap.kt b/en/codes/kotlin/chapter_heap/heap.kt index bed2b803d..69f8b4c6f 100644 --- a/en/codes/kotlin/chapter_heap/heap.kt +++ b/en/codes/kotlin/chapter_heap/heap.kt @@ -9,58 +9,74 @@ package chapter_heap import utils.printHeap import java.util.* -fun testPush(heap: Queue, _val: Int) { - heap.offer(_val) // Push an element onto the heap - print("\nAfter pushing $_val onto the heap:\n") - printHeap(heap) -} - -fun testPop(heap: Queue) { - val _val = heap.poll() // Pop the top element from the heap - print("\nAfter popping the top element $_val from the heap:\n") - printHeap(heap) -} - /* Driver code */ fun main() { + // [region]{init} /* Initialize heaps */ // Initialize a min heap var minHeap = PriorityQueue() - // Initialize a max heap by supplying a lambda expression as the Comparator val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + // [endregion]{init} println("\nThe following example uses a max heap") + // [region]{push} /* Push an element onto the heap */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + maxHeap.offer(1) + maxHeap.offer(3) + maxHeap.offer(2) + maxHeap.offer(5) + maxHeap.offer(4) + // [endregion]{push} + printHeap(maxHeap) + // [region]{peek} /* Get the top element of the heap */ - val peek = maxHeap.peek() + var peek = maxHeap.peek() // 5 + // [endregion]{peek} print("\nTop element of the heap: $peek\n") + // [region]{pop_1} /* Pop the top element from the heap */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // The elements are popped in descending order + peek = maxHeap.poll() // 5 + // [endregion]{pop_1} + println(peek) + // [region]{pop_2} + peek = maxHeap.poll() // 4 + // [endregion]{pop_2} + println(peek) + // [region]{pop_3} + peek = maxHeap.poll() // 3 + // [endregion]{pop_3} + println(peek) + // [region]{pop_4} + peek = maxHeap.poll() // 2 + // [endregion]{pop_4} + println(peek) + // [region]{pop_5} + peek = maxHeap.poll() // 1 + // [endregion]{pop_5} + println(peek) + // [region]{size} /* Get the heap size */ val size = maxHeap.size + // [endregion]{size} print("\nNumber of elements in the heap: $size\n") + // [region]{is_empty} /* Check whether the heap is empty */ val isEmpty = maxHeap.isEmpty() + // [endregion]{is_empty} print("\nIs the heap empty? $isEmpty\n") + // [region]{heapify} /* Build a heap from an input list */ // The time complexity is O(n), not O(nlogn) minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) + // [endregion]{heapify} println("\nAfter building a min heap from the input list:") printHeap(minHeap) } \ No newline at end of file diff --git a/en/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt b/en/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt index e8c717e8d..3a3c1dd36 100644 --- a/en/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt +++ b/en/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt @@ -6,12 +6,14 @@ package chapter_stack_and_queue +// [region]{doubly_list_node} /* 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 } +// [endregion]{doubly_list_node} /* Deque implemented with a doubly linked list */ class LinkedListDeque { @@ -162,4 +164,4 @@ fun main() { /* Check whether the deque is empty */ val isEmpty = deque.isEmpty() println("Is the deque empty? $isEmpty") -} \ No newline at end of file +} diff --git a/en/codes/kotlin/utils/ListNode.kt b/en/codes/kotlin/utils/ListNode.kt index 1bbb76f0a..9edbe355e 100644 --- a/en/codes/kotlin/utils/ListNode.kt +++ b/en/codes/kotlin/utils/ListNode.kt @@ -6,9 +6,11 @@ package utils +// [region]{list_node} /* Linked list node */ class ListNode(var _val: Int) { - var next: ListNode? = null + var next: ListNode? = null // Reference to the next node +// [endregion]{list_node} companion object { /* Deserialize an array into a linked list */ @@ -22,4 +24,6 @@ class ListNode(var _val: Int) { return dum.next } } -} \ No newline at end of file +// [region]{list_node_end} +} +// [endregion]{list_node_end} diff --git a/en/codes/python/chapter_heap/heap.py b/en/codes/python/chapter_heap/heap.py index b08768cec..22e8fb45d 100644 --- a/en/codes/python/chapter_heap/heap.py +++ b/en/codes/python/chapter_heap/heap.py @@ -13,59 +13,76 @@ from modules import print_heap import heapq -def test_push(heap: list, val: int, flag: int = 1): - heapq.heappush(heap, flag * val) # Push an element onto the heap - print(f"\nAfter pushing element {val} onto the heap:") - print_heap([flag * val for val in heap]) - - -def test_pop(heap: list, flag: int = 1): - val = flag * heapq.heappop(heap) # Pop the top element from the heap - print(f"\nAfter popping top element {val} from the heap:") - print_heap([flag * val for val in heap]) - - """Driver code""" if __name__ == "__main__": + # [region]{init} # Initialize a min heap min_heap, flag = [], 1 # Initialize a max heap max_heap, flag = [], -1 - print("\nThe following example uses a max heap") # Python's heapq module implements a min heap by default # 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 + # [endregion]{init} + print("\nThe following example uses a max heap") + # [region]{push} # Push an element onto the heap - test_push(max_heap, 1, flag) - test_push(max_heap, 3, flag) - test_push(max_heap, 2, flag) - test_push(max_heap, 5, flag) - test_push(max_heap, 4, flag) + 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) + # [endregion]{push} + print_heap([flag * val for val in max_heap]) + # [region]{peek} # Get the top element of the heap - peek: int = flag * max_heap[0] + peek: int = flag * max_heap[0] # 5 + # [endregion]{peek} print(f"\nTop element of the heap: {peek}") + # [region]{pop_1} # Pop the top element from the heap - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) + # The elements are popped in descending order + val = flag * heapq.heappop(max_heap) # 5 + # [endregion]{pop_1} + print(val) + # [region]{pop_2} + val = flag * heapq.heappop(max_heap) # 4 + # [endregion]{pop_2} + print(val) + # [region]{pop_3} + val = flag * heapq.heappop(max_heap) # 3 + # [endregion]{pop_3} + print(val) + # [region]{pop_4} + val = flag * heapq.heappop(max_heap) # 2 + # [endregion]{pop_4} + print(val) + # [region]{pop_5} + val = flag * heapq.heappop(max_heap) # 1 + # [endregion]{pop_5} + print(val) + # [region]{size} # Get the heap size size: int = len(max_heap) + # [endregion]{size} print(f"\nNumber of elements in the heap: {size}") + # [region]{is_empty} # Check whether the heap is empty is_empty: bool = not max_heap + # [endregion]{is_empty} print(f"\nIs the heap empty: {is_empty}") + # [region]{heapify} # Build a heap from an input list # The time complexity is O(n), not O(nlogn) - min_heap = [1, 3, 2, 5, 4] + min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) + # [endregion]{heapify} print("\nAfter building a min heap from the input list:") print_heap(min_heap) diff --git a/en/codes/python/chapter_stack_and_queue/linkedlist_deque.py b/en/codes/python/chapter_stack_and_queue/linkedlist_deque.py index 7c1cac75b..310fa82de 100644 --- a/en/codes/python/chapter_stack_and_queue/linkedlist_deque.py +++ b/en/codes/python/chapter_stack_and_queue/linkedlist_deque.py @@ -5,14 +5,16 @@ Author: krahets (krahets@163.com) """ +# [region]{doubly_list_node} class ListNode: """Doubly linked list node""" def __init__(self, val: int): """Constructor""" - self.val: int = val + 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 +# [endregion]{doubly_list_node} class LinkedListDeque: diff --git a/en/codes/python/modules/list_node.py b/en/codes/python/modules/list_node.py index 136ee2099..e12ddbb85 100644 --- a/en/codes/python/modules/list_node.py +++ b/en/codes/python/modules/list_node.py @@ -5,12 +5,14 @@ Author: krahets (krahets@163.com) """ +# [region]{list_node} 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 +# [endregion]{list_node} def list_to_linked_list(arr: list[int]) -> ListNode | None: 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..a151a9d27 100644 --- a/en/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/en/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,9 +4,10 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{doubly_list_node} ### Doubly linked list node class ListNode - attr_accessor :val + attr_accessor :val # Node value attr_accessor :next # Reference to the next node attr_accessor :prev # Reference to the previous node @@ -15,6 +16,7 @@ class ListNode @val = val end end +# [endregion]{doubly_list_node} ### Deque implemented with a doubly linked list ### class LinkedListDeque diff --git a/en/codes/ruby/utils/list_node.rb b/en/codes/ruby/utils/list_node.rb index d85c3cb72..0f23ea46d 100644 --- a/en/codes/ruby/utils/list_node.rb +++ b/en/codes/ruby/utils/list_node.rb @@ -4,6 +4,7 @@ Created Time: 2024-03-18 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{list_node} ### Linked list node class ### class ListNode attr_accessor :val # Node value @@ -14,6 +15,7 @@ class ListNode @next = next_node end end +# [endregion]{list_node} ### Deserialize a list into a linked list ### def arr_to_linked_list(arr) diff --git a/en/codes/rust/chapter_heap/heap.rs b/en/codes/rust/chapter_heap/heap.rs index c898129a3..9ac371ebe 100644 --- a/en/codes/rust/chapter_heap/heap.rs +++ b/en/codes/rust/chapter_heap/heap.rs @@ -6,22 +6,13 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::{cmp::Reverse, collections::BinaryHeap}; - -fn test_push_max(heap: &mut BinaryHeap, val: i32) { - heap.push(val); // Push an element onto the heap - println!("\nAfter pushing element {} into the heap", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} - -fn test_pop_max(heap: &mut BinaryHeap) { - let val = heap.pop().unwrap(); - println!("\nAfter removing the top element {} from the heap", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} +// [endregion]{import} /* Driver code */ fn main() { + // [region]{init} /* Initialize the heap */ // Initialize a min heap #[allow(unused_assignments)] @@ -29,43 +20,66 @@ fn main() { // Rust's BinaryHeap is a max heap; wrapping elements in Reverse gives min heap ordering // Initialize a max heap let mut max_heap = BinaryHeap::new(); + // [endregion]{init} println!("\nThe following example uses a max heap"); + // [region]{push} /* Push an element onto the heap */ - test_push_max(&mut max_heap, 1); - test_push_max(&mut max_heap, 3); - test_push_max(&mut max_heap, 2); - test_push_max(&mut max_heap, 5); - test_push_max(&mut max_heap, 4); + max_heap.push(1); + max_heap.push(3); + max_heap.push(2); + max_heap.push(5); + max_heap.push(4); + // [endregion]{push} + print_util::print_heap(max_heap.iter().map(|&val| val).collect()); + // [region]{peek} /* Get the top element of the heap */ - let peek = max_heap.peek().unwrap(); + let peek = max_heap.peek().unwrap(); // 5 + // [endregion]{peek} println!("\nTop element: {}", peek); + // [region]{pop_1} /* Pop the top element from the heap */ - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); + // The elements are popped in descending order + let peek = max_heap.pop().unwrap(); // 5 + // [endregion]{pop_1} + println!("{}", peek); + // [region]{pop_2} + let peek = max_heap.pop().unwrap(); // 4 + // [endregion]{pop_2} + println!("{}", peek); + // [region]{pop_3} + let peek = max_heap.pop().unwrap(); // 3 + // [endregion]{pop_3} + println!("{}", peek); + // [region]{pop_4} + let peek = max_heap.pop().unwrap(); // 2 + // [endregion]{pop_4} + println!("{}", peek); + // [region]{pop_5} + let peek = max_heap.pop().unwrap(); // 1 + // [endregion]{pop_5} + println!("{}", peek); + // [region]{size} /* Get the heap size */ let size = max_heap.len(); + // [endregion]{size} println!("\nNumber of heap elements: {}", size); + // [region]{is_empty} /* Check whether the heap is empty */ let is_empty = max_heap.is_empty(); + // [endregion]{is_empty} println!("\nIs the heap empty? {}", is_empty); + // [region]{heapify} /* Build a heap from an input list */ // The time complexity is O(n), not O(nlogn) - min_heap = BinaryHeap::from( - vec![1, 3, 2, 5, 4] - .into_iter() - .map(|val| Reverse(val)) - .collect::>>(), - ); + min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); + // [endregion]{heapify} println!("\nAfter building a min heap from the input list:"); print_util::print_heap(min_heap.iter().map(|&val| val.0).collect()); } diff --git a/en/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs b/en/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs index c02bf2bce..ae63a7761 100644 --- a/en/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs +++ b/en/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs @@ -6,9 +6,12 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::cell::RefCell; use std::rc::Rc; +// [endregion]{import} +// [region]{doubly_list_node} /* Doubly linked list node */ pub struct ListNode { pub val: T, // Node value @@ -25,6 +28,7 @@ impl ListNode { })) } } +// [endregion]{doubly_list_node} /* Deque implemented with a doubly linked list */ #[allow(dead_code)] diff --git a/en/codes/rust/src/include/list_node.rs b/en/codes/rust/src/include/list_node.rs index 143272994..4f89a7869 100644 --- a/en/codes/rust/src/include/list_node.rs +++ b/en/codes/rust/src/include/list_node.rs @@ -4,20 +4,26 @@ * Author: codingonion (coderonion@gmail.com), rongyi (hiarongyi@gmail.com) */ +// [region]{import_cell} use std::cell::RefCell; +// [endregion]{import_cell} use std::collections::HashMap; +// [region]{import_rc} use std::rc::Rc; +// [endregion]{import_rc} +// [region]{list_node} #[derive(Debug)] pub struct ListNode { - pub val: T, - pub next: Option>>>, + 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 })) } +// [endregion]{list_node} /* Deserialize an array into a linked list */ pub fn arr_to_linked_list(array: &[T]) -> Option>>> @@ -54,4 +60,6 @@ impl ListNode { hashmap } +// [region]{list_node_end} } +// [endregion]{list_node_end} 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 b84faf03a..ff3c57f4c 100644 --- a/en/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/en/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -1,52 +1,24 @@ ```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 +[file]{modules/list_node}-[region]{list_node} ``` ```cpp title="" -/* Linked list node structure */ -struct ListNode { - int val; // Node value - ListNode *next; // Pointer to the next node - ListNode(int x) : val(x), next(nullptr) {} // Constructor -}; +[file]{utils/list_node.hpp}-[region]{list_node} ``` ```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 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```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 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```go title="" -/* Linked list node structure */ -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 { - return &ListNode{ - Val: val, - Next: nil, - } -} +[file]{pkg/list_node}-[region]{list_node} ``` ```swift title="" @@ -62,84 +34,36 @@ class ListNode { ``` ```javascript title="" -/* Linked list node class */ -class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // Node value - this.next = (next === undefined ? null : next); // Reference to the next node - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```typescript title="" -/* Linked list node class */ -class ListNode { - val: number; - next: ListNode | null; - 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 - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```dart title="" -/* Linked list node class */ -class ListNode { - int val; // Node value - ListNode? next; // Reference to the next node - ListNode(this.val, [this.next]); // Constructor -} +[file]{utils/list_node}-[region]{list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; -/* Linked list node class */ -#[derive(Debug)] -struct ListNode { - val: i32, // Node value - next: Option>>, // Pointer to the next node -} +[file]{src/include/list_node}-[region]{import_cell} +[file]{src/include/list_node}-[region]{import_rc} + +[file]{src/include/list_node}-[region]{list_node} +[file]{src/include/list_node}-[region]{list_node_end} ``` ```c title="" -/* Linked list node structure */ -typedef struct ListNode { - int val; // Node value - struct ListNode *next; // Pointer to the next node -} ListNode; - -/* Constructor */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; -} +[file]{utils/list_node.h}-[region]{list_node} ``` ```kotlin title="" -/* Linked list node class */ -// Constructor -class ListNode(x: Int) { - val _val: Int = x // Node value - var next: ListNode? = null // Reference to the next node -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```ruby title="" -# Linked list node class -class ListNode - attr_accessor :val # Node value - attr_accessor :next # Reference to the next node - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end -end +[file]{utils/list_node}-[region]{list_node} ``` @@ -200,41 +124,19 @@ 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""" - 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 +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_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 -}; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```java title="" -/* Doubly linked list node class */ -class ListNode { - int val; // Node value - ListNode next; // Reference to the successor - ListNode prev; // Reference to the predecessor - ListNode(int x) { val = x; } // Constructor -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```go title="" @@ -256,117 +158,35 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* Doubly linked list node class */ -class ListNode { - var val: Int // Node value - var next: ListNode? // Reference to the successor - var prev: ListNode? // Reference to the predecessor - - init(x: Int) { // Constructor - val = x - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```javascript title="" -/* Doubly linked list node class */ -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 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```typescript title="" -/* Doubly linked list node class */ -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 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```dart title="" -/* Doubly linked list node class */ -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 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{import} -/* 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 -} - -/* Constructor */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; - -/* Constructor */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```ruby title="" -# Doubly linked list node class -class ListNode - attr_accessor :val # Node value - attr_accessor :next # Reference to the successor - attr_accessor :prev # Reference to the predecessor - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end -end +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` diff --git a/en/codes/snippets/chapter_heap/heap.md b/en/codes/snippets/chapter_heap/heap.md index b06e780f3..db8c5282e 100644 --- a/en/codes/snippets/chapter_heap/heap.md +++ b/en/codes/snippets/chapter_heap/heap.md @@ -1,256 +1,110 @@ ```python title="heap.py" -# Initialize a min heap -min_heap, flag = [], 1 -# Initialize a max heap -max_heap, flag = [], -1 +[file]{heap}-[region]{init} -# 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 +[file]{heap}-[region]{push} -# Insert elements into 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) +[file]{heap}-[region]{peek} -# Access the root element -peek: int = flag * max_heap[0] # 5 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_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 +[file]{heap}-[region]{size} -# Get the heap size -size: int = len(max_heap) +[file]{heap}-[region]{is_empty} -# Check whether the heap is empty -is_empty: bool = not max_heap - -# Build a heap from a list -min_heap: list[int] = [1, 3, 2, 5, 4] -heapq.heapify(min_heap) +[file]{heap}-[region]{heapify} ``` ```cpp title="heap.cpp" -/* Initialize a heap */ -// Initialize a min heap -priority_queue, greater> minHeap; -// Initialize a max heap -priority_queue, less> maxHeap; +[file]{heap}-[region]{init} -/* Insert elements into the heap */ -maxHeap.push(1); -maxHeap.push(3); -maxHeap.push(2); -maxHeap.push(5); -maxHeap.push(4); +[file]{heap}-[region]{push} -/* Access the root element */ -int peek = maxHeap.top(); // 5 +[file]{heap}-[region]{peek} -/* Remove root elements */ -// Removed elements form a descending sequence -maxHeap.pop(); // 5 -maxHeap.pop(); // 4 -maxHeap.pop(); // 3 -maxHeap.pop(); // 2 -maxHeap.pop(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Get the heap size */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* Check whether the heap is empty */ -bool isEmpty = maxHeap.empty(); +[file]{heap}-[region]{is_empty} -/* Build a heap from a list */ -vector input{1, 3, 2, 5, 4}; -minHeap = priority_queue, greater>(input.begin(), input.end()); +[file]{heap}-[region]{heapify} ``` ```java title="heap.java" -/* Initialize a heap */ -// Initialize a min heap -Queue minHeap = new PriorityQueue<>(); -// Initialize a max heap by changing the Comparator with a lambda expression -Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); +[file]{heap}-[region]{init} -/* Insert elements into the heap */ -maxHeap.offer(1); -maxHeap.offer(3); -maxHeap.offer(2); -maxHeap.offer(5); -maxHeap.offer(4); +[file]{heap}-[region]{push} -/* Access the root element */ -int peek = maxHeap.peek(); // 5 +[file]{heap}-[region]{peek} -/* Remove root elements */ -// Removed elements form a descending sequence -peek = maxHeap.poll(); // 5 -peek = maxHeap.poll(); // 4 -peek = maxHeap.poll(); // 3 -peek = maxHeap.poll(); // 2 -peek = maxHeap.poll(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Get the heap size */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* Check whether the heap is empty */ -boolean isEmpty = maxHeap.isEmpty(); +[file]{heap}-[region]{is_empty} -/* Build a heap from a list */ -minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +[file]{heap}-[region]{heapify} ``` ```csharp title="heap.cs" -/* Initialize a heap */ -// Initialize a min heap -PriorityQueue minHeap = new(); -// Initialize a max heap by changing the Comparer with a lambda expression -PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); +[file]{heap}-[region]{init} -/* Insert elements into the heap */ -maxHeap.Enqueue(1, 1); -maxHeap.Enqueue(3, 3); -maxHeap.Enqueue(2, 2); -maxHeap.Enqueue(5, 5); -maxHeap.Enqueue(4, 4); +[file]{heap}-[region]{push} -/* Access the root element */ -int peek = maxHeap.Peek();//5 +[file]{heap}-[region]{peek} -/* 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 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Get the heap size */ -int size = maxHeap.Count; +[file]{heap}-[region]{size} -/* Check whether the heap is empty */ -bool isEmpty = maxHeap.Count == 0; +[file]{heap}-[region]{is_empty} -/* Build a heap from a list */ -minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +[file]{heap}-[region]{heapify} ``` ```go title="heap.go" -// In Go, implement heap.Interface to build an integer max heap -// Implementing heap.Interface also requires implementing sort.Interface -type intHeap []any +[file]{heap}-[region]{int_heap} -// Push implements the heap.Interface method for inserting an element -func (h *intHeap) Push(x any) { - // Push and Pop use pointer receivers - // because they change 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 -func (h *intHeap) Pop() any { - // The element to remove has been placed at the end - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last -} - -// Len implements a sort.Interface method -func (h *intHeap) Len() int { - return len(*h) -} - -// Less implements a sort.Interface method -func (h *intHeap) Less(i, j int) bool { - // For a min heap, change this to a less-than comparison - return (*h)[i].(int) > (*h)[j].(int) -} - -// Swap implements a sort.Interface method -func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] -} - -// Top returns the root element -func (h *intHeap) Top() any { - return (*h)[0] -} - -/* Driver Code */ -func TestHeap(t *testing.T) { - /* Initialize a heap */ - // Initialize a max heap - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* Insert elements into the heap */ - // Call the heap.Interface methods to add elements - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* Access the root element */ - top := maxHeap.Top() - fmt.Printf("The root element is %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 - - /* Get the heap size */ - size := len(*maxHeap) - fmt.Printf("The heap contains %d elements\n", size) - - /* Check whether the heap is empty */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("Is the heap empty: %t\n", isEmpty) -} +[file]{heap_test}-[region]{test_heap} ``` ```swift title="heap.swift" -/* Initialize a heap */ -// Swift's Heap type supports both minimum and maximum operations and requires swift-collections -var heap = Heap() +[file]{heap}-[region]{import} -/* Insert elements into the heap */ -heap.insert(1) -heap.insert(3) -heap.insert(2) -heap.insert(5) -heap.insert(4) +[file]{heap}-[region]{init} -/* Access the root element */ -var peek = heap.max()! +[file]{heap}-[region]{push} -/* Remove root elements */ -peek = heap.removeMax() // 5 -peek = heap.removeMax() // 4 -peek = heap.removeMax() // 3 -peek = heap.removeMax() // 2 -peek = heap.removeMax() // 1 +[file]{heap}-[region]{peek} -/* Get the heap size */ -let size = heap.count +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Check whether the heap is empty */ -let isEmpty = heap.isEmpty +[file]{heap}-[region]{size} -/* Build a heap from a list */ -let heap2 = Heap([1, 3, 2, 5, 4]) +[file]{heap}-[region]{is_empty} + +[file]{heap}-[region]{heapify} ``` ```javascript title="heap.js" @@ -266,41 +120,25 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +[file]{heap}-[region]{import} -/* Initialize a heap */ -// Initialize a min heap -let mut min_heap = BinaryHeap::>::new(); -// Initialize a max heap -let mut max_heap = BinaryHeap::new(); +[file]{heap}-[region]{init} -/* Insert elements into the heap */ -max_heap.push(1); -max_heap.push(3); -max_heap.push(2); -max_heap.push(5); -max_heap.push(4); +[file]{heap}-[region]{push} -/* Access the root element */ -let peek = max_heap.peek().unwrap(); // 5 +[file]{heap}-[region]{peek} -/* 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 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Get the heap size */ -let size = max_heap.len(); +[file]{heap}-[region]{size} -/* Check whether the heap is empty */ -let is_empty = max_heap.is_empty(); +[file]{heap}-[region]{is_empty} -/* Build a heap from a list */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +[file]{heap}-[region]{heapify} ``` ```c title="heap.c" @@ -308,38 +146,23 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse ``` ```kotlin title="heap.kt" -/* Initialize a heap */ -// Initialize a min heap -var minHeap = PriorityQueue() -// Initialize a max heap by changing the Comparator with a lambda expression -val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } +[file]{heap}-[region]{init} -/* Insert elements into the heap */ -maxHeap.offer(1) -maxHeap.offer(3) -maxHeap.offer(2) -maxHeap.offer(5) -maxHeap.offer(4) +[file]{heap}-[region]{push} -/* Access the root element */ -var peek = maxHeap.peek() // 5 +[file]{heap}-[region]{peek} -/* Remove root elements */ -// Removed elements form a descending sequence -peek = maxHeap.poll() // 5 -peek = maxHeap.poll() // 4 -peek = maxHeap.poll() // 3 -peek = maxHeap.poll() // 2 -peek = maxHeap.poll() // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Get the heap size */ -val size = maxHeap.size +[file]{heap}-[region]{size} -/* Check whether the heap is empty */ -val isEmpty = maxHeap.isEmpty() +[file]{heap}-[region]{is_empty} -/* Build a heap from a list */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +[file]{heap}-[region]{heapify} ``` ```ruby title="heap.rb" diff --git a/en/codes/swift/chapter_heap/heap.swift b/en/codes/swift/chapter_heap/heap.swift index 0819b47a6..713713182 100644 --- a/en/codes/swift/chapter_heap/heap.swift +++ b/en/codes/swift/chapter_heap/heap.swift @@ -4,58 +4,76 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{import} import HeapModule +// [endregion]{import} import utils -func testPush(heap: inout Heap, val: Int) { - heap.insert(val) - print("\nAfter inserting element \(val) into the heap:\n") - PrintUtil.printHeap(queue: heap.unordered) -} - -func testPop(heap: inout Heap) { - let val = heap.removeMax() - print("\nAfter removing the maximum element \(val) from the heap:\n") - PrintUtil.printHeap(queue: heap.unordered) -} - @main enum _Heap { /* Driver code */ static func main() { + // [region]{init} /* Initialize the heap */ // The Heap type in Swift Collections supports both max heap and min heap operations var heap = Heap() + // [endregion]{init} + // [region]{push} /* Push an element onto the heap */ - testPush(heap: &heap, val: 1) - testPush(heap: &heap, val: 3) - testPush(heap: &heap, val: 2) - testPush(heap: &heap, val: 5) - testPush(heap: &heap, val: 4) + heap.insert(1) + heap.insert(3) + heap.insert(2) + heap.insert(5) + heap.insert(4) + // [endregion]{push} + PrintUtil.printHeap(queue: heap.unordered) + // [region]{peek} /* Get the maximum element of the heap */ - let peek = heap.max() + var peek = heap.max() + // [endregion]{peek} print("\nMaximum heap element: \(peek!)\n") + // [region]{pop_1} /* Remove the maximum element from the heap */ - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) + peek = heap.removeMax() // 5 + // [endregion]{pop_1} + print(peek!) + // [region]{pop_2} + peek = heap.removeMax() // 4 + // [endregion]{pop_2} + print(peek!) + // [region]{pop_3} + peek = heap.removeMax() // 3 + // [endregion]{pop_3} + print(peek!) + // [region]{pop_4} + peek = heap.removeMax() // 2 + // [endregion]{pop_4} + print(peek!) + // [region]{pop_5} + peek = heap.removeMax() // 1 + // [endregion]{pop_5} + print(peek!) + // [region]{size} /* Get the heap size */ let size = heap.count + // [endregion]{size} print("\nNumber of heap elements: \(size)\n") + // [region]{is_empty} /* Check whether the heap is empty */ let isEmpty = heap.isEmpty + // [endregion]{is_empty} print("\nIs the heap empty: \(isEmpty)\n") + // [region]{heapify} /* Build a heap from an input list */ // The time complexity is O(n), not O(nlogn) let heap2 = Heap([1, 3, 2, 5, 4]) + // [endregion]{heapify} print("\nAfter building a heap from the input list:") PrintUtil.printHeap(queue: heap2.unordered) } diff --git a/en/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift b/en/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift index 015efec18..8a134e768 100644 --- a/en/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift +++ b/en/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift @@ -4,6 +4,7 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{doubly_list_node} /* Doubly linked list node */ class ListNode { var val: Int // Node value @@ -14,6 +15,7 @@ class ListNode { self.val = val } } +// [endregion]{doubly_list_node} /* Deque implemented with a doubly linked list */ class LinkedListDeque { 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..624d5ff70 100644 --- a/en/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/en/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -4,10 +4,11 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* 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) { @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* Deque implemented with a doubly linked list */ class LinkedListDeque { diff --git a/en/codes/typescript/modules/ListNode.ts b/en/codes/typescript/modules/ListNode.ts index 20275c3ae..3f1ebb799 100644 --- a/en/codes/typescript/modules/ListNode.ts +++ b/en/codes/typescript/modules/ListNode.ts @@ -4,15 +4,17 @@ * Author: Justin (xiefahit@gmail.com) */ +// [region]{list_node} /* 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; this.next = next === undefined ? null : next; } } +// [endregion]{list_node} /* Deserialize an array into a linked list */ function arrToLinkedList(arr: number[]): ListNode | null { 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..645b876d7 100644 --- a/ja/codes/c/chapter_stack_and_queue/linkedlist_deque.c +++ b/ja/codes/c/chapter_stack_and_queue/linkedlist_deque.c @@ -6,6 +6,7 @@ #include "../utils/common.h" +// [region]{doubly_list_node} /* 双方向連結リストのノード */ typedef struct DoublyListNode { int val; // ノードの値 @@ -21,6 +22,7 @@ DoublyListNode *newDoublyListNode(int num) { new->prev = NULL; return new; } +// [endregion]{doubly_list_node} /* デストラクタ */ void delDoublyListNode(DoublyListNode *node) { diff --git a/ja/codes/c/utils/list_node.h b/ja/codes/c/utils/list_node.h index bb71448a3..197b2bbeb 100644 --- a/ja/codes/c/utils/list_node.h +++ b/ja/codes/c/utils/list_node.h @@ -11,6 +11,7 @@ extern "C" { #endif +// [region]{list_node} /* 連結リストのノードの構造体 */ typedef struct ListNode { int val; // ノードの値 @@ -25,6 +26,7 @@ ListNode *newListNode(int val) { node->next = NULL; return node; } +// [endregion]{list_node} /* 配列をデシリアライズして連結リストにする */ ListNode *arrToLinkedList(const int *arr, size_t size) { diff --git a/ja/codes/cpp/chapter_heap/heap.cpp b/ja/codes/cpp/chapter_heap/heap.cpp index 5fe845fd4..792b339ca 100644 --- a/ja/codes/cpp/chapter_heap/heap.cpp +++ b/ja/codes/cpp/chapter_heap/heap.cpp @@ -6,59 +6,75 @@ #include "../utils/common.hpp" -void testPush(priority_queue &heap, int val) { - heap.push(val); // ヒープに要素を挿入する - cout << "\n要素 " << val << " をヒープに挿入した後" << endl; - printHeap(heap); -} - -void testPop(priority_queue &heap) { - int val = heap.top(); - heap.pop(); - cout << "\nヒープの先頭要素 " << val << " を取り出した後" << endl; - printHeap(heap); -} - /* 実行用コード */ int main() { + // [region]{init} /* ヒープを初期化する */ // 最小ヒープを初期化する - // priority_queue, greater> minHeap; + priority_queue, greater> minHeap; // 最大ヒープを初期化する priority_queue, less> maxHeap; + // [endregion]{init} cout << "\n以下のテストケースは最大ヒープを対象とする" << endl; + // [region]{push} /* ヒープに要素を挿入する */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.push(1); + maxHeap.push(3); + maxHeap.push(2); + maxHeap.push(5); + maxHeap.push(4); + // [endregion]{push} + printHeap(maxHeap); + // [region]{peek} /* ヒープの先頭要素を取得する */ - int peek = maxHeap.top(); + int peek = maxHeap.top(); // 5 + // [endregion]{peek} cout << "\nヒープの先頭要素は " << peek << endl; + // [region]{pop_1} /* ヒープの先頭要素を取り出す */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // 取り出した要素は降順の列を形成する + maxHeap.pop(); // 5 + // [endregion]{pop_1} + printHeap(maxHeap); + // [region]{pop_2} + maxHeap.pop(); // 4 + // [endregion]{pop_2} + printHeap(maxHeap); + // [region]{pop_3} + maxHeap.pop(); // 3 + // [endregion]{pop_3} + printHeap(maxHeap); + // [region]{pop_4} + maxHeap.pop(); // 2 + // [endregion]{pop_4} + printHeap(maxHeap); + // [region]{pop_5} + maxHeap.pop(); // 1 + // [endregion]{pop_5} + printHeap(maxHeap); + // [region]{size} /* ヒープのサイズを取得する */ int size = maxHeap.size(); + // [endregion]{size} cout << "\nヒープの要素数は " << size << endl; + // [region]{is_empty} /* ヒープが空か判定 */ bool isEmpty = maxHeap.empty(); + // [endregion]{is_empty} cout << "\nヒープは空か " << isEmpty << endl; + // [region]{heapify} /* リストを入力してヒープを構築する */ // 時間計算量は O(n) であり、O(nlogn) ではない vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); + minHeap = priority_queue, greater>(input.begin(), input.end()); + // [endregion]{heapify} cout << "リストを入力して最小ヒープを構築した後" << endl; printHeap(minHeap); diff --git a/ja/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp b/ja/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp index f72bed5f7..13493d6f3 100644 --- a/ja/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp +++ b/ja/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp @@ -6,6 +6,7 @@ #include "../utils/common.hpp" +// [region]{doubly_list_node} /* 双方向連結リストのノード */ struct DoublyListNode { int val; // ノードの値 @@ -14,6 +15,7 @@ struct DoublyListNode { DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { } }; +// [endregion]{doubly_list_node} /* 双方向連結リストで実装した両端キュー */ class LinkedListDeque { diff --git a/ja/codes/cpp/utils/list_node.hpp b/ja/codes/cpp/utils/list_node.hpp index 7e536383e..f25bae7c6 100644 --- a/ja/codes/cpp/utils/list_node.hpp +++ b/ja/codes/cpp/utils/list_node.hpp @@ -11,13 +11,15 @@ using namespace std; +// [region]{list_node} /* 連結リストのノード */ struct ListNode { - int val; - ListNode *next; + int val; // ノードの値 + ListNode *next; // 後続ノードへのポインタ ListNode(int x) : val(x), next(nullptr) { } }; +// [endregion]{list_node} /* リストをデシリアライズして連結リストにする */ ListNode *vecToLinkedList(vector list) { diff --git a/ja/codes/csharp/chapter_heap/heap.cs b/ja/codes/csharp/chapter_heap/heap.cs index b22909ad5..b9e267bc7 100644 --- a/ja/codes/csharp/chapter_heap/heap.cs +++ b/ja/codes/csharp/chapter_heap/heap.cs @@ -7,57 +7,72 @@ namespace hello_algo.chapter_heap; public class heap { - void TestPush(PriorityQueue heap, int val) { - heap.Enqueue(val, val); // ヒープに要素を挿入する - Console.WriteLine($"\n要素 {val} をヒープに挿入した後\n"); - PrintUtil.PrintHeap(heap); - } - - void TestPop(PriorityQueue heap) { - int val = heap.Dequeue(); // ヒープの先頭要素を取り出す - Console.WriteLine($"\nヒープの先頭要素 {val} を取り出した後\n"); - PrintUtil.PrintHeap(heap); - } - [Test] public void Test() { + // [region]{init} /* ヒープを初期化する */ // 最小ヒープを初期化する PriorityQueue minHeap = new(); // 最大ヒープを初期化する(ラムダ式で Comparer を変更すればよい) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + // [endregion]{init} Console.WriteLine("以下のテストケースは最大ヒープを対象とする"); + // [region]{push} /* ヒープに要素を挿入する */ - TestPush(maxHeap, 1); - TestPush(maxHeap, 3); - TestPush(maxHeap, 2); - TestPush(maxHeap, 5); - TestPush(maxHeap, 4); + maxHeap.Enqueue(1, 1); + maxHeap.Enqueue(3, 3); + maxHeap.Enqueue(2, 2); + maxHeap.Enqueue(5, 5); + maxHeap.Enqueue(4, 4); + // [endregion]{push} + PrintUtil.PrintHeap(maxHeap); + // [region]{peek} /* ヒープの先頭要素を取得する */ - int peek = maxHeap.Peek(); + int peek = maxHeap.Peek(); // 5 + // [endregion]{peek} Console.WriteLine($"ヒープの先頭要素は {peek}"); + // [region]{pop_1} /* ヒープの先頭要素を取り出す */ // 取り出した要素は降順の列を形成する - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); + peek = maxHeap.Dequeue(); // 5 + // [endregion]{pop_1} + Console.WriteLine(peek); + // [region]{pop_2} + peek = maxHeap.Dequeue(); // 4 + // [endregion]{pop_2} + Console.WriteLine(peek); + // [region]{pop_3} + peek = maxHeap.Dequeue(); // 3 + // [endregion]{pop_3} + Console.WriteLine(peek); + // [region]{pop_4} + peek = maxHeap.Dequeue(); // 2 + // [endregion]{pop_4} + Console.WriteLine(peek); + // [region]{pop_5} + peek = maxHeap.Dequeue(); // 1 + // [endregion]{pop_5} + Console.WriteLine(peek); + // [region]{size} /* ヒープのサイズを取得する */ int size = maxHeap.Count; + // [endregion]{size} Console.WriteLine($"ヒープの要素数は {size}"); + // [region]{is_empty} /* ヒープが空か判定 */ bool isEmpty = maxHeap.Count == 0; + // [endregion]{is_empty} Console.WriteLine($"ヒープは空か {isEmpty}"); + // [region]{heapify} /* リストを入力してヒープを構築する */ - var list = new int[] { 1, 3, 2, 5, 4 }; - minHeap = new PriorityQueue(list.Select(x => (x, x))); + minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); + // [endregion]{heapify} Console.WriteLine("リストを入力して最小ヒープを構築した後"); PrintUtil.PrintHeap(minHeap); } diff --git a/ja/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs b/ja/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs index 87f6627c2..53ef50e52 100644 --- a/ja/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs +++ b/ja/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs @@ -6,12 +6,14 @@ namespace hello_algo.chapter_stack_and_queue; +// [region]{doubly_list_node} /* 双方向連結リストのノード */ public class ListNode(int val) { - public int val = val; // ノードの値 + public int val = val; // ノードの値 public ListNode? next = null; // 後続ノードへの参照 public ListNode? prev = null; // 前のノードへの参照 } +// [endregion]{doubly_list_node} /* 双方向連結リストで実装した両端キュー */ public class LinkedListDeque { diff --git a/ja/codes/csharp/utils/ListNode.cs b/ja/codes/csharp/utils/ListNode.cs index f2ca46681..0c039a3a0 100644 --- a/ja/codes/csharp/utils/ListNode.cs +++ b/ja/codes/csharp/utils/ListNode.cs @@ -4,10 +4,12 @@ namespace hello_algo.utils; +// [region]{list_node} /* 連結リストのノード */ public class ListNode(int x) { - public int val = x; - public ListNode? next; + public int val = x; // ノードの値 + public ListNode? next; // 次のノードへの参照 +// [endregion]{list_node} /* 配列をデシリアライズして連結リストにする */ public static ListNode? ArrToLinkedList(int[] arr) { @@ -29,4 +31,6 @@ public class ListNode(int x) { } return string.Join("->", list); } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/ja/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart b/ja/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart index 7eb2f6d6c..8714dfc21 100644 --- a/ja/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart +++ b/ja/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart @@ -4,6 +4,7 @@ * Author: liuyuxin (gvenusleo@gmail.com) */ +// [region]{doubly_list_node} /* 双方向連結リストのノード */ class ListNode { int val; // ノードの値 @@ -12,6 +13,7 @@ class ListNode { ListNode(this.val, {this.next, this.prev}); } +// [endregion]{doubly_list_node} /* 双方向連結リストで実装した両端キュー */ class LinkedListDeque { diff --git a/ja/codes/dart/utils/list_node.dart b/ja/codes/dart/utils/list_node.dart index 662cec106..77512abf6 100644 --- a/ja/codes/dart/utils/list_node.dart +++ b/ja/codes/dart/utils/list_node.dart @@ -4,13 +4,15 @@ * Author: Jefferson (JeffersonHuang77@gmail.com) */ +// [region]{list_node} /* 連結リストのノード */ class ListNode { - int val; - ListNode? next; + int val; // ノードの値 + ListNode? next; // 次のノードへの参照 - ListNode(this.val, [this.next]); + ListNode(this.val, [this.next]); // コンストラクタ } +// [endregion]{list_node} /* リストをデシリアライズして連結リストにする */ ListNode? listToLinkedList(List list) { diff --git a/ja/codes/go/chapter_heap/heap.go b/ja/codes/go/chapter_heap/heap.go index d8a7fd2cb..3b6f1f97c 100644 --- a/ja/codes/go/chapter_heap/heap.go +++ b/ja/codes/go/chapter_heap/heap.go @@ -4,6 +4,7 @@ package chapter_heap +// [region]{int_heap} // Go では heap.Interface を実装して整数の最大ヒープを構築できる // heap.Interface の実装には sort.Interface も実装する必要がある type intHeap []any @@ -43,3 +44,5 @@ func (h *intHeap) Swap(i, j int) { func (h *intHeap) Top() any { return (*h)[0] } + +// [endregion]{int_heap} diff --git a/ja/codes/go/chapter_heap/heap_test.go b/ja/codes/go/chapter_heap/heap_test.go index 9a2052a4f..2cfd1f7f7 100644 --- a/ja/codes/go/chapter_heap/heap_test.go +++ b/ja/codes/go/chapter_heap/heap_test.go @@ -13,42 +13,32 @@ import ( . "github.com/krahets/hello-algo/pkg" ) -func testPush(h *intHeap, val int) { - // heap.Interface の関数を呼び出し、要素を追加する - heap.Push(h, val) - fmt.Printf("\n要素 %d をヒープに挿入した後 \n", val) - PrintHeap(*h) -} - -func testPop(h *intHeap) { - // heap.Interface の関数を呼び出し、要素を取り除く - val := heap.Pop(h) - fmt.Printf("\nヒープの先頭要素 %d を取り出した後 \n", val) - PrintHeap(*h) -} - +// [region]{test_heap} func TestHeap(t *testing.T) { /* ヒープを初期化する */ // 最大ヒープを初期化する maxHeap := &intHeap{} heap.Init(maxHeap) /* ヒープに要素を挿入する */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + // heap.Interface の関数を呼び出し、要素を追加する + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) /* ヒープの先頭要素を取得する */ top := maxHeap.Top() fmt.Printf("ヒープの先頭要素は %d\n", top) /* ヒープの先頭要素を取り出す */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // heap.Interface の関数を呼び出し、要素を取り除く + fmt.Println(heap.Pop(maxHeap)) // 5 + fmt.Println(heap.Pop(maxHeap)) // 4 + fmt.Println(heap.Pop(maxHeap)) // 3 + fmt.Println(heap.Pop(maxHeap)) // 2 + fmt.Println(heap.Pop(maxHeap)) // 1 /* ヒープのサイズを取得する */ size := len(*maxHeap) @@ -59,6 +49,8 @@ func TestHeap(t *testing.T) { fmt.Printf("ヒープは空か %t\n", isEmpty) } +// [endregion]{test_heap} + func TestMyHeap(t *testing.T) { /* ヒープを初期化する */ // 最大ヒープを初期化する diff --git a/ja/codes/go/pkg/list_node.go b/ja/codes/go/pkg/list_node.go index f83129f35..dfa2bdd50 100644 --- a/ja/codes/go/pkg/list_node.go +++ b/ja/codes/go/pkg/list_node.go @@ -4,20 +4,23 @@ package pkg +// [region]{list_node} // ListNode は連結リストのノード type ListNode struct { - Next *ListNode - Val int + Val int // ノードの値 + Next *ListNode // 後続ノードへのポインタ } // NewListNode は連結リストのノードのコンストラクタ func NewListNode(v int) *ListNode { return &ListNode{ - Next: nil, Val: v, + Next: nil, } } +// [endregion]{list_node} + // ArrayToLinkedList は配列をデシリアライズして連結リストにする func ArrayToLinkedList(arr []int) *ListNode { // 連結リストのダミーの先頭ノード diff --git a/ja/codes/java/chapter_heap/heap.java b/ja/codes/java/chapter_heap/heap.java index b5f7897ce..acddb5ef0 100644 --- a/ja/codes/java/chapter_heap/heap.java +++ b/ja/codes/java/chapter_heap/heap.java @@ -10,56 +10,73 @@ import utils.*; import java.util.*; public class heap { - public static void testPush(Queue heap, int val) { - heap.offer(val); // ヒープに要素を挿入する - System.out.format("\n要素 %d をヒープに挿入した後\n", val); - PrintUtil.printHeap(heap); - } - - public static void testPop(Queue heap) { - int val = heap.poll(); // ヒープの先頭要素を取り出す - System.out.format("\nヒープの先頭要素 %d を取り出した後\n", val); - PrintUtil.printHeap(heap); - } - public static void main(String[] args) { + // [region]{init} /* ヒープを初期化する */ // 最小ヒープを初期化する Queue minHeap = new PriorityQueue<>(); // 最大ヒープを初期化する(ラムダ式で Comparator を変更すればよい) Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + // [endregion]{init} System.out.println("\n以下のテストケースは最大ヒープを対象とする"); + // [region]{push} /* ヒープに要素を挿入する */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.offer(1); + maxHeap.offer(3); + maxHeap.offer(2); + maxHeap.offer(5); + maxHeap.offer(4); + // [endregion]{push} + PrintUtil.printHeap(maxHeap); + // [region]{peek} /* ヒープの先頭要素を取得する */ - int peek = maxHeap.peek(); + int peek = maxHeap.peek(); // 5 + // [endregion]{peek} System.out.format("\nヒープの先頭要素は %d\n", peek); + // [region]{pop_1} /* ヒープの先頭要素を取り出す */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // 取り出した要素は降順の列を形成する + peek = maxHeap.poll(); // 5 + // [endregion]{pop_1} + System.out.println(peek); + // [region]{pop_2} + peek = maxHeap.poll(); // 4 + // [endregion]{pop_2} + System.out.println(peek); + // [region]{pop_3} + peek = maxHeap.poll(); // 3 + // [endregion]{pop_3} + System.out.println(peek); + // [region]{pop_4} + peek = maxHeap.poll(); // 2 + // [endregion]{pop_4} + System.out.println(peek); + // [region]{pop_5} + peek = maxHeap.poll(); // 1 + // [endregion]{pop_5} + System.out.println(peek); + // [region]{size} /* ヒープのサイズを取得する */ int size = maxHeap.size(); + // [endregion]{size} System.out.format("\nヒープの要素数は %d\n", size); + // [region]{is_empty} /* ヒープが空か判定 */ boolean isEmpty = maxHeap.isEmpty(); + // [endregion]{is_empty} System.out.format("\nヒープは空か %b\n", isEmpty); + // [region]{heapify} /* リストを入力してヒープを構築する */ // 時間計算量は O(n) であり、O(nlogn) ではない minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); + // [endregion]{heapify} System.out.println("\nリストを入力して最小ヒープを構築した後"); PrintUtil.printHeap(minHeap); } diff --git a/ja/codes/java/chapter_stack_and_queue/linkedlist_deque.java b/ja/codes/java/chapter_stack_and_queue/linkedlist_deque.java index e561502d1..e4c9b0885 100644 --- a/ja/codes/java/chapter_stack_and_queue/linkedlist_deque.java +++ b/ja/codes/java/chapter_stack_and_queue/linkedlist_deque.java @@ -8,9 +8,10 @@ package chapter_stack_and_queue; import java.util.*; +// [region]{doubly_list_node} /* 双方向連結リストのノード */ class ListNode { - int val; // ノードの値 + int val; // ノードの値 ListNode next; // 後続ノードへの参照 ListNode prev; // 前のノードへの参照 @@ -19,6 +20,7 @@ class ListNode { prev = next = null; } } +// [endregion]{doubly_list_node} /* 双方向連結リストで実装した両端キュー */ class LinkedListDeque { diff --git a/ja/codes/java/utils/ListNode.java b/ja/codes/java/utils/ListNode.java index de28f40d1..db45ade26 100644 --- a/ja/codes/java/utils/ListNode.java +++ b/ja/codes/java/utils/ListNode.java @@ -6,14 +6,16 @@ package utils; +// [region]{list_node} /* 連結リストのノード */ public class ListNode { - public int val; - public ListNode next; + public int val; // ノードの値 + public ListNode next; // 次のノードへの参照 public ListNode(int x) { val = x; } +// [endregion]{list_node} /* リストをデシリアライズして連結リストにする */ public static ListNode arrToLinkedList(int[] arr) { @@ -25,4 +27,6 @@ public class ListNode { } return dum.next; } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/ja/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js b/ja/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js index 0d5d32ca2..6ce14acdf 100644 --- a/ja/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js +++ b/ja/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js @@ -4,6 +4,7 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* 双方向連結リストのノード */ class ListNode { prev; // 前のノードへの参照(ポインタ) @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* 双方向連結リストで実装した両端キュー */ class LinkedListDeque { diff --git a/ja/codes/javascript/modules/ListNode.js b/ja/codes/javascript/modules/ListNode.js index fb5266cb4..068aef0b6 100644 --- a/ja/codes/javascript/modules/ListNode.js +++ b/ja/codes/javascript/modules/ListNode.js @@ -4,6 +4,7 @@ * Author: IsChristina (christinaxia77@foxmail.com) */ +// [region]{list_node} /* 連結リストのノード */ class ListNode { val; // ノードの値 @@ -13,6 +14,7 @@ class ListNode { this.next = next === undefined ? null : next; } } +// [endregion]{list_node} /* リストをデシリアライズして連結リストにする */ function arrToLinkedList(arr) { diff --git a/ja/codes/kotlin/chapter_heap/heap.kt b/ja/codes/kotlin/chapter_heap/heap.kt index d96e2f164..5f0c1bdc2 100644 --- a/ja/codes/kotlin/chapter_heap/heap.kt +++ b/ja/codes/kotlin/chapter_heap/heap.kt @@ -9,58 +9,74 @@ package chapter_heap import utils.printHeap import java.util.* -fun testPush(heap: Queue, _val: Int) { - heap.offer(_val) // ヒープに要素を挿入する - print("\n要素 $_val をヒープに挿入した後\n") - printHeap(heap) -} - -fun testPop(heap: Queue) { - val _val = heap.poll() // ヒープの先頭要素を取り出す - print("\nヒープの先頭要素 $_val を取り出した後\n") - printHeap(heap) -} - /* 実行用コード */ fun main() { + // [region]{init} /* ヒープを初期化する */ // 最小ヒープを初期化する var minHeap = PriorityQueue() - // 最大ヒープを初期化する(ラムダ式で Comparator を変更すればよい) val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + // [endregion]{init} println("\n以下のテストケースは最大ヒープを対象とする") + // [region]{push} /* ヒープに要素を挿入する */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + maxHeap.offer(1) + maxHeap.offer(3) + maxHeap.offer(2) + maxHeap.offer(5) + maxHeap.offer(4) + // [endregion]{push} + printHeap(maxHeap) + // [region]{peek} /* ヒープの先頭要素を取得する */ - val peek = maxHeap.peek() + var peek = maxHeap.peek() // 5 + // [endregion]{peek} print("\nヒープの先頭要素は $peek\n") + // [region]{pop_1} /* ヒープの先頭要素を取り出す */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // 取り出した要素は降順の列を形成する + peek = maxHeap.poll() // 5 + // [endregion]{pop_1} + println(peek) + // [region]{pop_2} + peek = maxHeap.poll() // 4 + // [endregion]{pop_2} + println(peek) + // [region]{pop_3} + peek = maxHeap.poll() // 3 + // [endregion]{pop_3} + println(peek) + // [region]{pop_4} + peek = maxHeap.poll() // 2 + // [endregion]{pop_4} + println(peek) + // [region]{pop_5} + peek = maxHeap.poll() // 1 + // [endregion]{pop_5} + println(peek) + // [region]{size} /* ヒープのサイズを取得する */ val size = maxHeap.size + // [endregion]{size} print("\nヒープの要素数は $size\n") + // [region]{is_empty} /* ヒープが空か判定 */ val isEmpty = maxHeap.isEmpty() + // [endregion]{is_empty} print("\nヒープは空か $isEmpty\n") + // [region]{heapify} /* リストを入力してヒープを構築する */ // 時間計算量は O(n) であり、O(nlogn) ではない minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) + // [endregion]{heapify} println("\nリストを入力して最小ヒープを構築した後") printHeap(minHeap) } \ No newline at end of file diff --git a/ja/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt b/ja/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt index 42004e9e2..94610c6de 100644 --- a/ja/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt +++ b/ja/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt @@ -6,12 +6,14 @@ package chapter_stack_and_queue +// [region]{doubly_list_node} /* 双方向連結リストのノード */ class ListNode(var _val: Int) { // ノードの値 var next: ListNode? = null // 後続ノードへの参照 var prev: ListNode? = null // 前のノードへの参照 } +// [endregion]{doubly_list_node} /* 双方向連結リストで実装した両端キュー */ class LinkedListDeque { @@ -162,4 +164,4 @@ fun main() { /* 両端キューが空かどうかを判定する */ val isEmpty = deque.isEmpty() println("両端キューは空か = $isEmpty") -} \ No newline at end of file +} diff --git a/ja/codes/kotlin/utils/ListNode.kt b/ja/codes/kotlin/utils/ListNode.kt index dbb4cdacf..7e6952462 100644 --- a/ja/codes/kotlin/utils/ListNode.kt +++ b/ja/codes/kotlin/utils/ListNode.kt @@ -6,9 +6,11 @@ package utils +// [region]{list_node} /* 連結リストのノード */ class ListNode(var _val: Int) { - var next: ListNode? = null + var next: ListNode? = null // 次のノードへの参照 +// [endregion]{list_node} companion object { /* リストをデシリアライズして連結リストにする */ @@ -22,4 +24,6 @@ class ListNode(var _val: Int) { return dum.next } } -} \ No newline at end of file +// [region]{list_node_end} +} +// [endregion]{list_node_end} diff --git a/ja/codes/python/chapter_heap/heap.py b/ja/codes/python/chapter_heap/heap.py index a469d195a..1de051163 100644 --- a/ja/codes/python/chapter_heap/heap.py +++ b/ja/codes/python/chapter_heap/heap.py @@ -13,59 +13,76 @@ from modules import print_heap import heapq -def test_push(heap: list, val: int, flag: int = 1): - heapq.heappush(heap, flag * val) # ヒープに要素を挿入する - print(f"\n要素 {val} をヒープに挿入した後") - print_heap([flag * val for val in heap]) - - -def test_pop(heap: list, flag: int = 1): - val = flag * heapq.heappop(heap) # ヒープの先頭要素を取り出す - print(f"\nヒープの先頭要素 {val} を取り出した後") - print_heap([flag * val for val in heap]) - - """実行用コード""" if __name__ == "__main__": + # [region]{init} # 最小ヒープを初期化する min_heap, flag = [], 1 # 最大ヒープを初期化する max_heap, flag = [], -1 - print("\n以下のテストケースは最大ヒープを対象とする") # Python の heapq モジュールは既定で最小ヒープを実装する # 「要素の符号を反転」してからヒープに挿入すれば、大小関係が逆転し、最大ヒープを実装できる # この例では flag = 1 が最小ヒープ、flag = -1 が最大ヒープに対応する + # [endregion]{init} + print("\n以下のテストケースは最大ヒープを対象とする") + # [region]{push} # ヒープに要素を挿入する - test_push(max_heap, 1, flag) - test_push(max_heap, 3, flag) - test_push(max_heap, 2, flag) - test_push(max_heap, 5, flag) - test_push(max_heap, 4, flag) + 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) + # [endregion]{push} + print_heap([flag * val for val in max_heap]) + # [region]{peek} # ヒープの先頭要素を取得する - peek: int = flag * max_heap[0] + peek: int = flag * max_heap[0] # 5 + # [endregion]{peek} print(f"\nヒープの先頭要素は {peek}") + # [region]{pop_1} # ヒープの先頭要素を取り出す - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) + # 取り出した要素は降順の列を形成する + val = flag * heapq.heappop(max_heap) # 5 + # [endregion]{pop_1} + print(val) + # [region]{pop_2} + val = flag * heapq.heappop(max_heap) # 4 + # [endregion]{pop_2} + print(val) + # [region]{pop_3} + val = flag * heapq.heappop(max_heap) # 3 + # [endregion]{pop_3} + print(val) + # [region]{pop_4} + val = flag * heapq.heappop(max_heap) # 2 + # [endregion]{pop_4} + print(val) + # [region]{pop_5} + val = flag * heapq.heappop(max_heap) # 1 + # [endregion]{pop_5} + print(val) + # [region]{size} # ヒープのサイズを取得する size: int = len(max_heap) + # [endregion]{size} print(f"\nヒープの要素数は {size}") + # [region]{is_empty} # ヒープが空か判定 is_empty: bool = not max_heap + # [endregion]{is_empty} print(f"\nヒープは空か {is_empty}") + # [region]{heapify} # リストを入力してヒープを構築する # 時間計算量は O(n) であり、O(nlogn) ではない - min_heap = [1, 3, 2, 5, 4] + min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) + # [endregion]{heapify} print("\nリストを入力して最小ヒープを構築した後") print_heap(min_heap) diff --git a/ja/codes/python/chapter_stack_and_queue/linkedlist_deque.py b/ja/codes/python/chapter_stack_and_queue/linkedlist_deque.py index 12c01b568..0081ed595 100644 --- a/ja/codes/python/chapter_stack_and_queue/linkedlist_deque.py +++ b/ja/codes/python/chapter_stack_and_queue/linkedlist_deque.py @@ -5,14 +5,16 @@ Author: krahets (krahets@163.com) """ +# [region]{doubly_list_node} 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 # 前のノードへの参照 +# [endregion]{doubly_list_node} class LinkedListDeque: diff --git a/ja/codes/python/modules/list_node.py b/ja/codes/python/modules/list_node.py index 8a10f4a4c..c3d38b291 100644 --- a/ja/codes/python/modules/list_node.py +++ b/ja/codes/python/modules/list_node.py @@ -5,12 +5,14 @@ Author: krahets (krahets@163.com) """ +# [region]{list_node} class ListNode: """連結リストのノードクラス""" def __init__(self, val: int): self.val: int = val # ノードの値 - self.next: ListNode | None = None # 後続ノードへの参照 + self.next: ListNode | None = None # 次のノードへの参照 +# [endregion]{list_node} def list_to_linked_list(arr: list[int]) -> ListNode | None: 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..780618a31 100644 --- a/ja/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/ja/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,9 +4,10 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{doubly_list_node} ### 双方向連結リストのノード class ListNode - attr_accessor :val + attr_accessor :val # ノードの値 attr_accessor :next # 後続ノードへの参照 attr_accessor :prev # 前のノードへの参照 @@ -15,6 +16,7 @@ class ListNode @val = val end end +# [endregion]{doubly_list_node} ### 双方向連結リストで実装した両端キュー ### class LinkedListDeque diff --git a/ja/codes/ruby/utils/list_node.rb b/ja/codes/ruby/utils/list_node.rb index 986735872..7e05bac2e 100644 --- a/ja/codes/ruby/utils/list_node.rb +++ b/ja/codes/ruby/utils/list_node.rb @@ -4,6 +4,7 @@ Created Time: 2024-03-18 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{list_node} ### 連結リストのノードクラス ### class ListNode attr_accessor :val # ノードの値 @@ -14,6 +15,7 @@ class ListNode @next = next_node end end +# [endregion]{list_node} ### リストをデシリアライズして連結リストにする ### def arr_to_linked_list(arr) diff --git a/ja/codes/rust/chapter_heap/heap.rs b/ja/codes/rust/chapter_heap/heap.rs index 87cb82d23..06e9dc9a7 100644 --- a/ja/codes/rust/chapter_heap/heap.rs +++ b/ja/codes/rust/chapter_heap/heap.rs @@ -6,22 +6,13 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::{cmp::Reverse, collections::BinaryHeap}; - -fn test_push_max(heap: &mut BinaryHeap, val: i32) { - heap.push(val); // ヒープに要素を挿入する - println!("\n要素 {} をヒープに挿入した後", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} - -fn test_pop_max(heap: &mut BinaryHeap) { - let val = heap.pop().unwrap(); - println!("\nヒープの先頭要素 {} を取り出した後", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} +// [endregion]{import} /* 実行用コード */ fn main() { + // [region]{init} /* ヒープを初期化する */ // 最小ヒープを初期化する #[allow(unused_assignments)] @@ -29,43 +20,66 @@ fn main() { // Rust の BinaryHeap は最大ヒープであり、最小ヒープには通常 Reverse を「かぶせる」 // 最大ヒープを初期化する let mut max_heap = BinaryHeap::new(); + // [endregion]{init} println!("\n以下のテストケースは最大ヒープを対象とする"); + // [region]{push} /* ヒープに要素を挿入する */ - test_push_max(&mut max_heap, 1); - test_push_max(&mut max_heap, 3); - test_push_max(&mut max_heap, 2); - test_push_max(&mut max_heap, 5); - test_push_max(&mut max_heap, 4); + max_heap.push(1); + max_heap.push(3); + max_heap.push(2); + max_heap.push(5); + max_heap.push(4); + // [endregion]{push} + print_util::print_heap(max_heap.iter().map(|&val| val).collect()); + // [region]{peek} /* ヒープの先頭要素を取得する */ - let peek = max_heap.peek().unwrap(); + let peek = max_heap.peek().unwrap(); // 5 + // [endregion]{peek} println!("\nヒープの先頭要素は {}", peek); + // [region]{pop_1} /* ヒープの先頭要素を取り出す */ - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); + // 取り出した要素は降順の列を形成する + let peek = max_heap.pop().unwrap(); // 5 + // [endregion]{pop_1} + println!("{}", peek); + // [region]{pop_2} + let peek = max_heap.pop().unwrap(); // 4 + // [endregion]{pop_2} + println!("{}", peek); + // [region]{pop_3} + let peek = max_heap.pop().unwrap(); // 3 + // [endregion]{pop_3} + println!("{}", peek); + // [region]{pop_4} + let peek = max_heap.pop().unwrap(); // 2 + // [endregion]{pop_4} + println!("{}", peek); + // [region]{pop_5} + let peek = max_heap.pop().unwrap(); // 1 + // [endregion]{pop_5} + println!("{}", peek); + // [region]{size} /* ヒープのサイズを取得する */ let size = max_heap.len(); + // [endregion]{size} println!("\nヒープの要素数は {}", size); + // [region]{is_empty} /* ヒープが空か判定 */ let is_empty = max_heap.is_empty(); + // [endregion]{is_empty} println!("\nヒープは空か {}", is_empty); + // [region]{heapify} /* リストを入力してヒープを構築する */ // 時間計算量は O(n) であり、O(nlogn) ではない - min_heap = BinaryHeap::from( - vec![1, 3, 2, 5, 4] - .into_iter() - .map(|val| Reverse(val)) - .collect::>>(), - ); + min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); + // [endregion]{heapify} println!("\nリストを入力して最小ヒープを構築した後"); print_util::print_heap(min_heap.iter().map(|&val| val.0).collect()); } diff --git a/ja/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs b/ja/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs index 06126a9ff..baeaf82fa 100644 --- a/ja/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs +++ b/ja/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs @@ -6,9 +6,12 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::cell::RefCell; use std::rc::Rc; +// [endregion]{import} +// [region]{doubly_list_node} /* 双方向連結リストのノード */ pub struct ListNode { pub val: T, // ノードの値 @@ -25,6 +28,7 @@ impl ListNode { })) } } +// [endregion]{doubly_list_node} /* 双方向連結リストで実装した両端キュー */ #[allow(dead_code)] diff --git a/ja/codes/rust/src/include/list_node.rs b/ja/codes/rust/src/include/list_node.rs index 05af74829..1df8244ba 100644 --- a/ja/codes/rust/src/include/list_node.rs +++ b/ja/codes/rust/src/include/list_node.rs @@ -4,20 +4,26 @@ * Author: codingonion (coderonion@gmail.com), rongyi (hiarongyi@gmail.com) */ +// [region]{import_cell} use std::cell::RefCell; +// [endregion]{import_cell} use std::collections::HashMap; +// [region]{import_rc} use std::rc::Rc; +// [endregion]{import_rc} +// [region]{list_node} #[derive(Debug)] pub struct ListNode { - pub val: T, - pub next: Option>>>, + pub val: T, // ノードの値 + pub next: Option>>>, // 後続ノードへのポインタ } impl ListNode { pub fn new(val: T) -> Rc>> { Rc::new(RefCell::new(ListNode { val, next: None })) } +// [endregion]{list_node} /* 配列をデシリアライズして連結リストにする */ pub fn arr_to_linked_list(array: &[T]) -> Option>>> @@ -54,4 +60,6 @@ impl ListNode { hashmap } +// [region]{list_node_end} } +// [endregion]{list_node_end} 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 d8d0598d9..c48cf94dc 100644 --- a/ja/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/ja/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -1,52 +1,24 @@ ```python title="" -class ListNode: - """連結リストのノードクラス""" - def __init__(self, val: int): - self.val: int = val # ノードの値 - self.next: ListNode | None = None # 次のノードへの参照 +[file]{modules/list_node}-[region]{list_node} ``` ```cpp title="" -/* 連結リストのノード構造体 */ -struct ListNode { - int val; // ノードの値 - ListNode *next; // 次のノードへのポインタ - ListNode(int x) : val(x), next(nullptr) {} // コンストラクタ -}; +[file]{utils/list_node.hpp}-[region]{list_node} ``` ```java title="" -/* 連結リストのノードクラス */ -class ListNode { - int val; // ノードの値 - ListNode next; // 次のノードへの参照 - ListNode(int x) { val = x; } // コンストラクタ -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```csharp title="" -/* 連結リストのノードクラス */ -class ListNode(int x) { //コンストラクタ - public int val = x; // ノードの値 - public ListNode? next; // 次のノードへの参照 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```go title="" -/* 連結リストのノード構造体 */ -type ListNode struct { - Val int // ノードの値 - Next *ListNode // 次のノードへのポインタ -} - -// NewListNode コンストラクタで、新しい連結リストを作る -func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } -} +[file]{pkg/list_node}-[region]{list_node} ``` ```swift title="" @@ -62,84 +34,36 @@ class ListNode { ``` ```javascript title="" -/* 連結リストのノードクラス */ -class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // ノードの値 - this.next = (next === undefined ? null : next); // 次のノードへの参照 - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```typescript title="" -/* 連結リストのノードクラス */ -class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // ノードの値 - this.next = next === undefined ? null : next; // 次のノードへの参照 - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```dart title="" -/* 連結リストのノードクラス */ -class ListNode { - int val; // ノードの値 - ListNode? next; // 次のノードへの参照 - ListNode(this.val, [this.next]); // コンストラクタ -} +[file]{utils/list_node}-[region]{list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; -/* 連結リストのノードクラス */ -#[derive(Debug)] -struct ListNode { - val: i32, // ノードの値 - next: Option>>, // 次のノードへのポインタ -} +[file]{src/include/list_node}-[region]{import_cell} +[file]{src/include/list_node}-[region]{import_rc} + +[file]{src/include/list_node}-[region]{list_node} +[file]{src/include/list_node}-[region]{list_node_end} ``` ```c title="" -/* 連結リストのノード構造体 */ -typedef struct ListNode { - int val; // ノードの値 - struct ListNode *next; // 次のノードへのポインタ -} ListNode; - -/* コンストラクタ */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; -} +[file]{utils/list_node.h}-[region]{list_node} ``` ```kotlin title="" -/* 連結リストのノードクラス */ -// コンストラクタ -class ListNode(x: Int) { - val _val: Int = x // ノードの値 - var next: ListNode? = null // 次のノードへの参照 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```ruby title="" -# 連結リストのノードクラス -class ListNode - attr_accessor :val # ノードの値 - attr_accessor :next # 次のノードへの参照 - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end -end +[file]{utils/list_node}-[region]{list_node} ``` @@ -200,41 +124,19 @@ 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 # 先行ノードへの参照 +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```cpp title="" -/* 双方向連結リストのノード構造体 */ -struct ListNode { - int val; // ノードの値 - ListNode *next; // 後続ノードへのポインタ - ListNode *prev; // 先行ノードへのポインタ - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // コンストラクタ -}; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```java title="" -/* 双方向連結リストのノードクラス */ -class ListNode { - int val; // ノードの値 - ListNode next; // 後続ノードへの参照 - ListNode prev; // 先行ノードへの参照 - ListNode(int x) { val = x; } // コンストラクタ -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```csharp title="" -/* 双方向連結リストのノードクラス */ -class ListNode(int x) { // コンストラクタ - public int val = x; // ノードの値 - public ListNode? next; // 後続ノードへの参照 - public ListNode? prev; // 先行ノードへの参照 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```go title="" @@ -256,117 +158,35 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* 双方向連結リストのノードクラス */ -class ListNode { - var val: Int // ノードの値 - var next: ListNode? // 後続ノードへの参照 - var prev: ListNode? // 先行ノードへの参照 - - init(x: Int) { // コンストラクタ - val = x - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // 先行ノードへの参照 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // 先行ノードへの参照 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```dart title="" -/* 双方向連結リストのノードクラス */ -class ListNode { - int val; // ノードの値 - ListNode? next; // 後続ノードへの参照 - ListNode? prev; // 先行ノードへの参照 - ListNode(this.val, [this.next, this.prev]); // コンストラクタ -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{import} -/* 双方向連結リストのノード型 */ -#[derive(Debug)] -struct ListNode { - val: i32, // ノードの値 - next: Option>>, // 後続ノードへのポインタ - prev: Option>>, // 先行ノードへのポインタ -} - -/* コンストラクタ */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```c title="" -/* 双方向連結リストのノード構造体 */ -typedef struct ListNode { - int val; // ノードの値 - struct ListNode *next; // 後続ノードへのポインタ - struct ListNode *prev; // 先行ノードへのポインタ -} ListNode; - -/* コンストラクタ */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```kotlin title="" -/* 双方向連結リストのノードクラス */ -// コンストラクタ -class ListNode(x: Int) { - val _val: Int = x // ノードの値 - var next: ListNode? = null // 後続ノードへの参照 - var prev: ListNode? = null // 先行ノードへの参照 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```ruby title="" -# 双方向連結リストのノードクラス -class ListNode - attr_accessor :val # ノードの値 - attr_accessor :next # 後続ノードへの参照 - attr_accessor :prev # 先行ノードへの参照 - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end -end +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` diff --git a/ja/codes/snippets/chapter_heap/heap.md b/ja/codes/snippets/chapter_heap/heap.md index 511d7b632..4323acaf1 100644 --- a/ja/codes/snippets/chapter_heap/heap.md +++ b/ja/codes/snippets/chapter_heap/heap.md @@ -1,256 +1,110 @@ ```python title="heap.py" -# 最小ヒープを初期化 -min_heap, flag = [], 1 -# 最大ヒープを初期化 -max_heap, flag = [], -1 +[file]{heap}-[region]{init} -# Python の heapq モジュールはデフォルトで最小ヒープを実装する -# 要素の符号を反転してから挿入すると、大小関係が逆転し最大ヒープを実現できる -# この例では flag = 1 が最小ヒープ、flag = -1 が最大ヒープに対応する +[file]{heap}-[region]{push} -# 要素をヒープに挿入 -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) +[file]{heap}-[region]{peek} -# ヒープの先頭要素を取得 -peek: int = flag * max_heap[0] # 5 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_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 +[file]{heap}-[region]{size} -# ヒープの要素数を取得 -size: int = len(max_heap) +[file]{heap}-[region]{is_empty} -# ヒープが空かどうかを判定 -is_empty: bool = not max_heap - -# リストを入力してヒープを構築 -min_heap: list[int] = [1, 3, 2, 5, 4] -heapq.heapify(min_heap) +[file]{heap}-[region]{heapify} ``` ```cpp title="heap.cpp" -/* ヒープを初期化 */ -// 最小ヒープを初期化 -priority_queue, greater> minHeap; -// 最大ヒープを初期化 -priority_queue, less> maxHeap; +[file]{heap}-[region]{init} -/* 要素をヒープに挿入 */ -maxHeap.push(1); -maxHeap.push(3); -maxHeap.push(2); -maxHeap.push(5); -maxHeap.push(4); +[file]{heap}-[region]{push} -/* ヒープの先頭要素を取得 */ -int peek = maxHeap.top(); // 5 +[file]{heap}-[region]{peek} -/* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる -maxHeap.pop(); // 5 -maxHeap.pop(); // 4 -maxHeap.pop(); // 3 -maxHeap.pop(); // 2 -maxHeap.pop(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* ヒープの要素数を取得 */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* ヒープが空かどうかを判定 */ -bool isEmpty = maxHeap.empty(); +[file]{heap}-[region]{is_empty} -/* リストを入力してヒープを構築 */ -vector input{1, 3, 2, 5, 4}; -minHeap = priority_queue, greater>(input.begin(), input.end()); +[file]{heap}-[region]{heapify} ``` ```java title="heap.java" -/* ヒープを初期化 */ -// 最小ヒープを初期化 -Queue minHeap = new PriorityQueue<>(); -// 最大ヒープを初期化(ラムダ式で Comparator を変更する) -Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); +[file]{heap}-[region]{init} -/* 要素をヒープに挿入 */ -maxHeap.offer(1); -maxHeap.offer(3); -maxHeap.offer(2); -maxHeap.offer(5); -maxHeap.offer(4); +[file]{heap}-[region]{push} -/* ヒープの先頭要素を取得 */ -int peek = maxHeap.peek(); // 5 +[file]{heap}-[region]{peek} -/* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる -peek = maxHeap.poll(); // 5 -peek = maxHeap.poll(); // 4 -peek = maxHeap.poll(); // 3 -peek = maxHeap.poll(); // 2 -peek = maxHeap.poll(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* ヒープの要素数を取得 */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* ヒープが空かどうかを判定 */ -boolean isEmpty = maxHeap.isEmpty(); +[file]{heap}-[region]{is_empty} -/* リストを入力してヒープを構築 */ -minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +[file]{heap}-[region]{heapify} ``` ```csharp title="heap.cs" -/* ヒープを初期化 */ -// 最小ヒープを初期化 -PriorityQueue minHeap = new(); -// 最大ヒープを初期化(ラムダ式で Comparer を変更する) -PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); +[file]{heap}-[region]{init} -/* 要素をヒープに挿入 */ -maxHeap.Enqueue(1, 1); -maxHeap.Enqueue(3, 3); -maxHeap.Enqueue(2, 2); -maxHeap.Enqueue(5, 5); -maxHeap.Enqueue(4, 4); +[file]{heap}-[region]{push} -/* ヒープの先頭要素を取得 */ -int peek = maxHeap.Peek();//5 +[file]{heap}-[region]{peek} -/* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* ヒープの要素数を取得 */ -int size = maxHeap.Count; +[file]{heap}-[region]{size} -/* ヒープが空かどうかを判定 */ -bool isEmpty = maxHeap.Count == 0; +[file]{heap}-[region]{is_empty} -/* リストを入力してヒープを構築 */ -minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +[file]{heap}-[region]{heapify} ``` ```go title="heap.go" -// Go では heap.Interface を実装して整数の最大ヒープを構築できる -// heap.Interface の実装には sort.Interface の実装も必要 -type intHeap []any +[file]{heap}-[region]{int_heap} -// Push は heap.Interface のメソッドで、ヒープへの挿入を実装する -func (h *intHeap) Push(x any) { - // Push と Pop はポインタレシーバーを引数として使う - // スライスの内容だけでなく長さも変更するため - *h = append(*h, x.(int)) -} - -// Pop は heap.Interface のメソッドで、先頭要素の取り出しを実装する -func (h *intHeap) Pop() any { - // 取り出す要素は末尾に格納されている - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last -} - -// Len は sort.Interface のメソッド -func (h *intHeap) Len() int { - return len(*h) -} - -// Less は sort.Interface のメソッド -func (h *intHeap) Less(i, j int) bool { - // 最小ヒープを実装する場合は、小なり記号に変更する - return (*h)[i].(int) > (*h)[j].(int) -} - -// Swap は sort.Interface のメソッド -func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] -} - -// Top ヒープの先頭要素を取得 -func (h *intHeap) Top() any { - return (*h)[0] -} - -/* 実行用コード */ -func TestHeap(t *testing.T) { - /* ヒープを初期化 */ - // 最大ヒープを初期化 - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* 要素をヒープに挿入 */ - // heap.Interface のメソッドを呼んで要素を追加 - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* ヒープの先頭要素を取得 */ - 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 - - /* ヒープの要素数を取得 */ - size := len(*maxHeap) - fmt.Printf("ヒープの要素数は %d\n", size) - - /* ヒープが空かどうかを判定 */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("ヒープは空か %t\n", isEmpty) -} +[file]{heap_test}-[region]{test_heap} ``` ```swift title="heap.swift" -/* ヒープを初期化 */ -// Swift の Heap 型は最大ヒープと最小ヒープの両方に対応し、swift-collections の導入が必要 -var heap = Heap() +[file]{heap}-[region]{import} -/* 要素をヒープに挿入 */ -heap.insert(1) -heap.insert(3) -heap.insert(2) -heap.insert(5) -heap.insert(4) +[file]{heap}-[region]{init} -/* ヒープの先頭要素を取得 */ -var peek = heap.max()! +[file]{heap}-[region]{push} -/* ヒープの先頭要素を取り出す */ -peek = heap.removeMax() // 5 -peek = heap.removeMax() // 4 -peek = heap.removeMax() // 3 -peek = heap.removeMax() // 2 -peek = heap.removeMax() // 1 +[file]{heap}-[region]{peek} -/* ヒープの要素数を取得 */ -let size = heap.count +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* ヒープが空かどうかを判定 */ -let isEmpty = heap.isEmpty +[file]{heap}-[region]{size} -/* リストを入力してヒープを構築 */ -let heap2 = Heap([1, 3, 2, 5, 4]) +[file]{heap}-[region]{is_empty} + +[file]{heap}-[region]{heapify} ``` ```javascript title="heap.js" @@ -266,41 +120,25 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +[file]{heap}-[region]{import} -/* ヒープを初期化 */ -// 最小ヒープを初期化 -let mut min_heap = BinaryHeap::>::new(); -// 最大ヒープを初期化 -let mut max_heap = BinaryHeap::new(); +[file]{heap}-[region]{init} -/* 要素をヒープに挿入 */ -max_heap.push(1); -max_heap.push(3); -max_heap.push(2); -max_heap.push(5); -max_heap.push(4); +[file]{heap}-[region]{push} -/* ヒープの先頭要素を取得 */ -let peek = max_heap.peek().unwrap(); // 5 +[file]{heap}-[region]{peek} -/* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる -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 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* ヒープの要素数を取得 */ -let size = max_heap.len(); +[file]{heap}-[region]{size} -/* ヒープが空かどうかを判定 */ -let is_empty = max_heap.is_empty(); +[file]{heap}-[region]{is_empty} -/* リストを入力してヒープを構築 */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +[file]{heap}-[region]{heapify} ``` ```c title="heap.c" @@ -308,38 +146,23 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse ``` ```kotlin title="heap.kt" -/* ヒープを初期化 */ -// 最小ヒープを初期化 -var minHeap = PriorityQueue() -// 最大ヒープを初期化(ラムダ式で Comparator を変更する) -val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } +[file]{heap}-[region]{init} -/* 要素をヒープに挿入 */ -maxHeap.offer(1) -maxHeap.offer(3) -maxHeap.offer(2) -maxHeap.offer(5) -maxHeap.offer(4) +[file]{heap}-[region]{push} -/* ヒープの先頭要素を取得 */ -var peek = maxHeap.peek() // 5 +[file]{heap}-[region]{peek} -/* ヒープの先頭要素を取り出す */ -// 取り出した要素は降順の列になる -peek = maxHeap.poll() // 5 -peek = maxHeap.poll() // 4 -peek = maxHeap.poll() // 3 -peek = maxHeap.poll() // 2 -peek = maxHeap.poll() // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* ヒープの要素数を取得 */ -val size = maxHeap.size +[file]{heap}-[region]{size} -/* ヒープが空かどうかを判定 */ -val isEmpty = maxHeap.isEmpty() +[file]{heap}-[region]{is_empty} -/* リストを入力してヒープを構築 */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +[file]{heap}-[region]{heapify} ``` ```ruby title="heap.rb" diff --git a/ja/codes/swift/chapter_heap/heap.swift b/ja/codes/swift/chapter_heap/heap.swift index aacea4cae..37a03fb81 100644 --- a/ja/codes/swift/chapter_heap/heap.swift +++ b/ja/codes/swift/chapter_heap/heap.swift @@ -4,58 +4,76 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{import} import HeapModule +// [endregion]{import} import utils -func testPush(heap: inout Heap, val: Int) { - heap.insert(val) - print("\n要素 \(val) をヒープに挿入した後\n") - PrintUtil.printHeap(queue: heap.unordered) -} - -func testPop(heap: inout Heap) { - let val = heap.removeMax() - print("\nヒープの先頭要素 \(val) を取り出した後\n") - PrintUtil.printHeap(queue: heap.unordered) -} - @main enum _Heap { /* 実行用コード */ static func main() { + // [region]{init} /* ヒープを初期化する */ // Swift の Heap 型は最大ヒープと最小ヒープの両方に対応する var heap = Heap() + // [endregion]{init} + // [region]{push} /* ヒープに要素を挿入する */ - testPush(heap: &heap, val: 1) - testPush(heap: &heap, val: 3) - testPush(heap: &heap, val: 2) - testPush(heap: &heap, val: 5) - testPush(heap: &heap, val: 4) + heap.insert(1) + heap.insert(3) + heap.insert(2) + heap.insert(5) + heap.insert(4) + // [endregion]{push} + PrintUtil.printHeap(queue: heap.unordered) + // [region]{peek} /* ヒープの先頭要素を取得する */ - let peek = heap.max() + var peek = heap.max() + // [endregion]{peek} print("\nヒープの先頭要素は \(peek!)\n") + // [region]{pop_1} /* ヒープの先頭要素を取り出す */ - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) + peek = heap.removeMax() // 5 + // [endregion]{pop_1} + print(peek!) + // [region]{pop_2} + peek = heap.removeMax() // 4 + // [endregion]{pop_2} + print(peek!) + // [region]{pop_3} + peek = heap.removeMax() // 3 + // [endregion]{pop_3} + print(peek!) + // [region]{pop_4} + peek = heap.removeMax() // 2 + // [endregion]{pop_4} + print(peek!) + // [region]{pop_5} + peek = heap.removeMax() // 1 + // [endregion]{pop_5} + print(peek!) + // [region]{size} /* ヒープのサイズを取得する */ let size = heap.count + // [endregion]{size} print("\nヒープの要素数は \(size)\n") + // [region]{is_empty} /* ヒープが空か判定 */ let isEmpty = heap.isEmpty + // [endregion]{is_empty} print("\nヒープは空か \(isEmpty)\n") + // [region]{heapify} /* リストを入力してヒープを構築する */ // 時間計算量は O(n) であり、O(nlogn) ではない let heap2 = Heap([1, 3, 2, 5, 4]) + // [endregion]{heapify} print("\nリストを入力してヒープを構築した後") PrintUtil.printHeap(queue: heap2.unordered) } diff --git a/ja/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift b/ja/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift index c9d258e9d..e2ddf88e7 100644 --- a/ja/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift +++ b/ja/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift @@ -4,6 +4,7 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{doubly_list_node} /* 双方向連結リストのノード */ class ListNode { var val: Int // ノードの値 @@ -14,6 +15,7 @@ class ListNode { self.val = val } } +// [endregion]{doubly_list_node} /* 双方向連結リストで実装した両端キュー */ class LinkedListDeque { 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..963fd68b7 100644 --- a/ja/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/ja/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -4,10 +4,11 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* 双方向連結リストのノード */ class ListNode { - prev: ListNode; // 前のノードへの参照(ポインタ) - next: ListNode; // 後続ノードへの参照(ポインタ) + prev: ListNode | null; // 前のノードへの参照(ポインタ) + next: ListNode | null; // 後続ノードへの参照(ポインタ) val: number; // ノードの値 constructor(val: number) { @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* 双方向連結リストで実装した両端キュー */ class LinkedListDeque { diff --git a/ja/codes/typescript/modules/ListNode.ts b/ja/codes/typescript/modules/ListNode.ts index b7c4b91fe..ebf519c6a 100644 --- a/ja/codes/typescript/modules/ListNode.ts +++ b/ja/codes/typescript/modules/ListNode.ts @@ -4,15 +4,17 @@ * Author: Justin (xiefahit@gmail.com) */ +// [region]{list_node} /* 連結リストのノード */ 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; } } +// [endregion]{list_node} /* 配列をデシリアライズして連結リストにする */ function arrToLinkedList(arr: number[]): ListNode | null { 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..a181b6d36 100644 --- a/ko/codes/c/chapter_stack_and_queue/linkedlist_deque.c +++ b/ko/codes/c/chapter_stack_and_queue/linkedlist_deque.c @@ -6,6 +6,7 @@ #include "../utils/common.h" +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ typedef struct DoublyListNode { int val; // 노드 값 @@ -21,6 +22,7 @@ DoublyListNode *newDoublyListNode(int num) { new->prev = NULL; return new; } +// [endregion]{doubly_list_node} /* 소멸자 */ void delDoublyListNode(DoublyListNode *node) { diff --git a/ko/codes/c/utils/list_node.h b/ko/codes/c/utils/list_node.h index 23203a5fb..c0a7069bf 100644 --- a/ko/codes/c/utils/list_node.h +++ b/ko/codes/c/utils/list_node.h @@ -11,6 +11,7 @@ extern "C" { #endif +// [region]{list_node} /* 연결 리스트 노드 구조체 */ typedef struct ListNode { int val; // 노드 값 @@ -25,6 +26,7 @@ ListNode *newListNode(int val) { node->next = NULL; return node; } +// [endregion]{list_node} /* 배열을 역직렬화하여 연결 리스트로 변환한다 */ ListNode *arrToLinkedList(const int *arr, size_t size) { diff --git a/ko/codes/cpp/chapter_heap/heap.cpp b/ko/codes/cpp/chapter_heap/heap.cpp index af9f2a96b..829ad9bd7 100644 --- a/ko/codes/cpp/chapter_heap/heap.cpp +++ b/ko/codes/cpp/chapter_heap/heap.cpp @@ -6,59 +6,75 @@ #include "../utils/common.hpp" -void testPush(priority_queue &heap, int val) { - heap.push(val); // 힙에 원소 삽입 - cout << "\n원소 " << val << " 힙에 삽입 후" << endl; - printHeap(heap); -} - -void testPop(priority_queue &heap) { - int val = heap.top(); - heap.pop(); - cout << "\n힙의 루트 원소 " << val << " 힙에서 꺼낸 후" << endl; - printHeap(heap); -} - /* 실행 코드 */ int main() { + // [region]{init} /* 힙 초기화 */ // 최소 힙 초기화 - // priority_queue, greater> minHeap; + priority_queue, greater> minHeap; // 최대 힙 초기화 priority_queue, less> maxHeap; + // [endregion]{init} cout << "\n다음 테스트 예제는 최대 힙이다" << endl; + // [region]{push} /* 힙에 원소 삽입 */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.push(1); + maxHeap.push(3); + maxHeap.push(2); + maxHeap.push(5); + maxHeap.push(4); + // [endregion]{push} + printHeap(maxHeap); + // [region]{peek} /* 힙의 루트 원소 반환 */ - int peek = maxHeap.top(); + int peek = maxHeap.top(); // 5 + // [endregion]{peek} cout << "\n힙의 루트 원소: " << peek << endl; + // [region]{pop_1} /* 힙의 루트 원소 꺼내기 */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 + maxHeap.pop(); // 5 + // [endregion]{pop_1} + printHeap(maxHeap); + // [region]{pop_2} + maxHeap.pop(); // 4 + // [endregion]{pop_2} + printHeap(maxHeap); + // [region]{pop_3} + maxHeap.pop(); // 3 + // [endregion]{pop_3} + printHeap(maxHeap); + // [region]{pop_4} + maxHeap.pop(); // 2 + // [endregion]{pop_4} + printHeap(maxHeap); + // [region]{pop_5} + maxHeap.pop(); // 1 + // [endregion]{pop_5} + printHeap(maxHeap); + // [region]{size} /* 힙 크기 반환 */ int size = maxHeap.size(); + // [endregion]{size} cout << "\n힙의 원소 개수: " << size << endl; + // [region]{is_empty} /* 힙이 비어 있는지 판단 */ bool isEmpty = maxHeap.empty(); + // [endregion]{is_empty} cout << "\n힙이 비어 있는가: " << isEmpty << endl; + // [region]{heapify} /* 리스트를 입력하여 힙 구성 */ // 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); + minHeap = priority_queue, greater>(input.begin(), input.end()); + // [endregion]{heapify} cout << "리스트를 입력하여 최소 힙을 구성한 후" << endl; printHeap(minHeap); 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..1b8cb7fba 100644 --- a/ko/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp +++ b/ko/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp @@ -6,6 +6,7 @@ #include "../utils/common.hpp" +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ struct DoublyListNode { int val; // 노드 값 @@ -14,6 +15,7 @@ struct DoublyListNode { DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { } }; +// [endregion]{doubly_list_node} /* 이중 연결 리스트로 구현한 덱 */ class LinkedListDeque { diff --git a/ko/codes/cpp/utils/list_node.hpp b/ko/codes/cpp/utils/list_node.hpp index 9c972ab3a..2a9ab4c90 100644 --- a/ko/codes/cpp/utils/list_node.hpp +++ b/ko/codes/cpp/utils/list_node.hpp @@ -11,13 +11,15 @@ using namespace std; +// [region]{list_node} /* 연결 리스트 노드 */ struct ListNode { - int val; - ListNode *next; + int val; // 노드 값 + ListNode *next; // 다음 노드 포인터 ListNode(int x) : val(x), next(nullptr) { } }; +// [endregion]{list_node} /* 리스트를 연결 리스트로 역직렬화 */ ListNode *vecToLinkedList(vector list) { diff --git a/ko/codes/csharp/chapter_heap/heap.cs b/ko/codes/csharp/chapter_heap/heap.cs index 81be32fec..17b1c8207 100644 --- a/ko/codes/csharp/chapter_heap/heap.cs +++ b/ko/codes/csharp/chapter_heap/heap.cs @@ -7,57 +7,72 @@ namespace hello_algo.chapter_heap; public class heap { - void TestPush(PriorityQueue heap, int val) { - heap.Enqueue(val, val); // 힙에 원소 삽입 - Console.WriteLine($"\n힙에 원소를 삽입한 후(원소: {val})\n"); - PrintUtil.PrintHeap(heap); - } - - void TestPop(PriorityQueue heap) { - int val = heap.Dequeue(); // 힙의 루트 원소 꺼내기 - Console.WriteLine($"\n힙의 루트 원소를 꺼낸 후(원소: {val})\n"); - PrintUtil.PrintHeap(heap); - } - [Test] public void Test() { + // [region]{init} /* 힙 초기화 */ // 최소 힙 초기화 PriorityQueue minHeap = new(); // 최대 힙 초기화(람다 식으로 Comparer를 변경하면 된다) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + // [endregion]{init} Console.WriteLine("다음 테스트 예제는 최대 힙이다"); + // [region]{push} /* 힙에 원소 삽입 */ - TestPush(maxHeap, 1); - TestPush(maxHeap, 3); - TestPush(maxHeap, 2); - TestPush(maxHeap, 5); - TestPush(maxHeap, 4); + maxHeap.Enqueue(1, 1); + maxHeap.Enqueue(3, 3); + maxHeap.Enqueue(2, 2); + maxHeap.Enqueue(5, 5); + maxHeap.Enqueue(4, 4); + // [endregion]{push} + PrintUtil.PrintHeap(maxHeap); + // [region]{peek} /* 힙의 루트 원소 반환 */ - int peek = maxHeap.Peek(); + int peek = maxHeap.Peek(); // 5 + // [endregion]{peek} Console.WriteLine($"힙의 루트 원소: {peek}"); + // [region]{pop_1} /* 힙의 루트 원소 꺼내기 */ // 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); + peek = maxHeap.Dequeue(); // 5 + // [endregion]{pop_1} + Console.WriteLine(peek); + // [region]{pop_2} + peek = maxHeap.Dequeue(); // 4 + // [endregion]{pop_2} + Console.WriteLine(peek); + // [region]{pop_3} + peek = maxHeap.Dequeue(); // 3 + // [endregion]{pop_3} + Console.WriteLine(peek); + // [region]{pop_4} + peek = maxHeap.Dequeue(); // 2 + // [endregion]{pop_4} + Console.WriteLine(peek); + // [region]{pop_5} + peek = maxHeap.Dequeue(); // 1 + // [endregion]{pop_5} + Console.WriteLine(peek); + // [region]{size} /* 힙 크기 반환 */ int size = maxHeap.Count; + // [endregion]{size} Console.WriteLine($"힙의 원소 개수: {size}"); + // [region]{is_empty} /* 힙이 비어 있는지 판단 */ bool isEmpty = maxHeap.Count == 0; + // [endregion]{is_empty} Console.WriteLine($"힙이 비어 있는가: {isEmpty}"); + // [region]{heapify} /* 리스트를 입력하여 힙 구성 */ - var list = new int[] { 1, 3, 2, 5, 4 }; - minHeap = new PriorityQueue(list.Select(x => (x, x))); + minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); + // [endregion]{heapify} Console.WriteLine("리스트를 입력하여 최소 힙을 구성한 후"); PrintUtil.PrintHeap(minHeap); } 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..1327adf61 100644 --- a/ko/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs +++ b/ko/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs @@ -6,12 +6,14 @@ namespace hello_algo.chapter_stack_and_queue; +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ public class ListNode(int val) { - public int val = val; // 노드 값 + public int val = val; // 노드 값 public ListNode? next = null; // 다음 노드 참조 public ListNode? prev = null; // 이전 노드 참조 } +// [endregion]{doubly_list_node} /* 이중 연결 리스트로 구현한 덱 */ public class LinkedListDeque { diff --git a/ko/codes/csharp/utils/ListNode.cs b/ko/codes/csharp/utils/ListNode.cs index 73377aa38..aca32474d 100644 --- a/ko/codes/csharp/utils/ListNode.cs +++ b/ko/codes/csharp/utils/ListNode.cs @@ -4,10 +4,12 @@ namespace hello_algo.utils; +// [region]{list_node} /* 연결 리스트 노드 */ public class ListNode(int x) { - public int val = x; - public ListNode? next; + public int val = x; // 노드 값 + public ListNode? next; // 다음 노드를 가리키는 참조 +// [endregion]{list_node} /* 배열을 역직렬화하여 연결 리스트로 변환한다 */ public static ListNode? ArrToLinkedList(int[] arr) { @@ -29,4 +31,6 @@ public class ListNode(int x) { } return string.Join("->", list); } +// [region]{list_node_end} } +// [endregion]{list_node_end} 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..7d99e17ad 100644 --- a/ko/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart +++ b/ko/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart @@ -4,6 +4,7 @@ * Author: liuyuxin (gvenusleo@gmail.com) */ +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ class ListNode { int val; // 노드 값 @@ -12,6 +13,7 @@ class ListNode { ListNode(this.val, {this.next, this.prev}); } +// [endregion]{doubly_list_node} /* 이중 연결 리스트로 구현한 덱 */ class LinkedListDeque { diff --git a/ko/codes/dart/utils/list_node.dart b/ko/codes/dart/utils/list_node.dart index 00ea129a0..c42e1999c 100644 --- a/ko/codes/dart/utils/list_node.dart +++ b/ko/codes/dart/utils/list_node.dart @@ -4,13 +4,15 @@ * Author: Jefferson (JeffersonHuang77@gmail.com) */ +// [region]{list_node} /* 연결 리스트 노드 */ class ListNode { - int val; - ListNode? next; + int val; // 노드 값 + ListNode? next; // 다음 노드를 가리키는 참조 - ListNode(this.val, [this.next]); + ListNode(this.val, [this.next]); // 생성자 } +// [endregion]{list_node} /* 리스트를 연결 리스트로 역직렬화 */ ListNode? listToLinkedList(List list) { diff --git a/ko/codes/go/chapter_heap/heap.go b/ko/codes/go/chapter_heap/heap.go index 88bd096a3..5bdb2cb45 100644 --- a/ko/codes/go/chapter_heap/heap.go +++ b/ko/codes/go/chapter_heap/heap.go @@ -4,6 +4,7 @@ package chapter_heap +// [region]{int_heap} // Go에서는 heap.Interface를 구현하여 정수 최대 힙을 만들 수 있다 // heap.Interface를 구현하려면 sort.Interface도 구현해야 한다 type intHeap []any @@ -43,3 +44,5 @@ func (h *intHeap) Swap(i, j int) { func (h *intHeap) Top() any { return (*h)[0] } + +// [endregion]{int_heap} diff --git a/ko/codes/go/chapter_heap/heap_test.go b/ko/codes/go/chapter_heap/heap_test.go index 247e3dc79..4eab46391 100644 --- a/ko/codes/go/chapter_heap/heap_test.go +++ b/ko/codes/go/chapter_heap/heap_test.go @@ -13,42 +13,32 @@ import ( . "github.com/krahets/hello-algo/pkg" ) -func testPush(h *intHeap, val int) { - // heap.Interface의 함수를 호출하여 원소를 추가한다 - heap.Push(h, val) - fmt.Printf("\n원소 %d 삽입 후의 힙\n", val) - PrintHeap(*h) -} - -func testPop(h *intHeap) { - // heap.Interface의 함수를 호출하여 원소를 제거한다 - val := heap.Pop(h) - fmt.Printf("\n루트 원소 %d 삭제 후의 힙\n", val) - PrintHeap(*h) -} - +// [region]{test_heap} func TestHeap(t *testing.T) { /* 힙 초기화 */ // 최대 힙 초기화 maxHeap := &intHeap{} heap.Init(maxHeap) /* 힙에 원소 삽입 */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + // heap.Interface의 함수를 호출하여 원소를 추가한다 + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) /* 힙의 루트 원소 반환 */ top := maxHeap.Top() fmt.Printf("힙의 루트 원소: %d\n", top) /* 힙의 루트 원소 꺼내기 */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // heap.Interface의 함수를 호출하여 원소를 제거한다 + fmt.Println(heap.Pop(maxHeap)) // 5 + fmt.Println(heap.Pop(maxHeap)) // 4 + fmt.Println(heap.Pop(maxHeap)) // 3 + fmt.Println(heap.Pop(maxHeap)) // 2 + fmt.Println(heap.Pop(maxHeap)) // 1 /* 힙 크기 반환 */ size := len(*maxHeap) @@ -59,6 +49,8 @@ func TestHeap(t *testing.T) { fmt.Printf("힙이 비어 있는가: %t\n", isEmpty) } +// [endregion]{test_heap} + func TestMyHeap(t *testing.T) { /* 힙 초기화 */ // 최대 힙 초기화 diff --git a/ko/codes/go/pkg/list_node.go b/ko/codes/go/pkg/list_node.go index 795e21ec1..7a3aa18e5 100644 --- a/ko/codes/go/pkg/list_node.go +++ b/ko/codes/go/pkg/list_node.go @@ -4,20 +4,23 @@ package pkg +// [region]{list_node} // ListNode: 연결 리스트 노드 type ListNode struct { - Next *ListNode - Val int + Val int // 노드 값 + Next *ListNode // 다음 노드 포인터 } // NewListNode: 연결 리스트 노드 생성자 func NewListNode(v int) *ListNode { return &ListNode{ - Next: nil, Val: v, + Next: nil, } } +// [endregion]{list_node} + // ArrayToLinkedList: 배열을 역직렬화하여 연결 리스트로 만든다 func ArrayToLinkedList(arr []int) *ListNode { // 연결 리스트의 더미 머리 노드 diff --git a/ko/codes/java/chapter_heap/heap.java b/ko/codes/java/chapter_heap/heap.java index c2ee87d72..3b6a22ee7 100644 --- a/ko/codes/java/chapter_heap/heap.java +++ b/ko/codes/java/chapter_heap/heap.java @@ -10,56 +10,73 @@ import utils.*; import java.util.*; public class heap { - public static void testPush(Queue heap, int val) { - heap.offer(val); // 힙에 원소 삽입 - System.out.format("\n원소를 힙에 삽입한 후(원소: %d)\n", val); - PrintUtil.printHeap(heap); - } - - public static void testPop(Queue heap) { - int val = heap.poll(); // 힙의 루트 원소 꺼내기 - System.out.format("\n힙의 루트 원소를 꺼낸 후(원소: %d)\n", val); - PrintUtil.printHeap(heap); - } - public static void main(String[] args) { + // [region]{init} /* 힙 초기화 */ // 최소 힙 초기화 Queue minHeap = new PriorityQueue<>(); // 최대 힙 초기화(lambda 식으로 Comparator를 수정하면 된다) Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + // [endregion]{init} System.out.println("\n다음 테스트 예제는 최대 힙이다"); + // [region]{push} /* 힙에 원소 삽입 */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.offer(1); + maxHeap.offer(3); + maxHeap.offer(2); + maxHeap.offer(5); + maxHeap.offer(4); + // [endregion]{push} + PrintUtil.printHeap(maxHeap); + // [region]{peek} /* 힙의 루트 원소 반환 */ - int peek = maxHeap.peek(); + int peek = maxHeap.peek(); // 5 + // [endregion]{peek} System.out.format("\n힙의 루트 원소: %d\n", peek); + // [region]{pop_1} /* 힙의 루트 원소 꺼내기 */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 + peek = maxHeap.poll(); // 5 + // [endregion]{pop_1} + System.out.println(peek); + // [region]{pop_2} + peek = maxHeap.poll(); // 4 + // [endregion]{pop_2} + System.out.println(peek); + // [region]{pop_3} + peek = maxHeap.poll(); // 3 + // [endregion]{pop_3} + System.out.println(peek); + // [region]{pop_4} + peek = maxHeap.poll(); // 2 + // [endregion]{pop_4} + System.out.println(peek); + // [region]{pop_5} + peek = maxHeap.poll(); // 1 + // [endregion]{pop_5} + System.out.println(peek); + // [region]{size} /* 힙 크기 반환 */ int size = maxHeap.size(); + // [endregion]{size} System.out.format("\n힙의 원소 개수: %d\n", size); + // [region]{is_empty} /* 힙이 비어 있는지 판단 */ boolean isEmpty = maxHeap.isEmpty(); + // [endregion]{is_empty} System.out.format("\n힙이 비어 있는가: %b\n", isEmpty); + // [region]{heapify} /* 리스트를 입력하여 힙 구성 */ // 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); + // [endregion]{heapify} System.out.println("\n리스트를 입력하여 최소 힙을 구성한 후"); PrintUtil.printHeap(minHeap); } 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..190bd9a99 100644 --- a/ko/codes/java/chapter_stack_and_queue/linkedlist_deque.java +++ b/ko/codes/java/chapter_stack_and_queue/linkedlist_deque.java @@ -8,9 +8,10 @@ package chapter_stack_and_queue; import java.util.*; +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ class ListNode { - int val; // 노드 값 + int val; // 노드 값 ListNode next; // 다음 노드 참조 ListNode prev; // 이전 노드 참조 @@ -19,6 +20,7 @@ class ListNode { prev = next = null; } } +// [endregion]{doubly_list_node} /* 이중 연결 리스트로 구현한 덱 */ class LinkedListDeque { diff --git a/ko/codes/java/utils/ListNode.java b/ko/codes/java/utils/ListNode.java index d463838f0..2a33a47ba 100644 --- a/ko/codes/java/utils/ListNode.java +++ b/ko/codes/java/utils/ListNode.java @@ -6,14 +6,16 @@ package utils; +// [region]{list_node} /* 연결 리스트 노드 */ public class ListNode { - public int val; - public ListNode next; + public int val; // 노드 값 + public ListNode next; // 다음 노드를 가리키는 참조 public ListNode(int x) { val = x; } +// [endregion]{list_node} /* 리스트를 연결 리스트로 역직렬화 */ public static ListNode arrToLinkedList(int[] arr) { @@ -25,4 +27,6 @@ public class ListNode { } return dum.next; } +// [region]{list_node_end} } +// [endregion]{list_node_end} 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..390d77df8 100644 --- a/ko/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js +++ b/ko/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js @@ -4,6 +4,7 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ class ListNode { prev; // 이전 노드 참조(포인터) @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* 이중 연결 리스트로 구현한 덱 */ class LinkedListDeque { diff --git a/ko/codes/javascript/modules/ListNode.js b/ko/codes/javascript/modules/ListNode.js index b785a154b..6e8bb4057 100644 --- a/ko/codes/javascript/modules/ListNode.js +++ b/ko/codes/javascript/modules/ListNode.js @@ -4,6 +4,7 @@ * Author: IsChristina (christinaxia77@foxmail.com) */ +// [region]{list_node} /* 연결 리스트 노드 */ class ListNode { val; // 노드 값 @@ -13,6 +14,7 @@ class ListNode { this.next = next === undefined ? null : next; } } +// [endregion]{list_node} /* 리스트를 연결 리스트로 역직렬화 */ function arrToLinkedList(arr) { diff --git a/ko/codes/kotlin/chapter_heap/heap.kt b/ko/codes/kotlin/chapter_heap/heap.kt index c494cbeb6..2cc3a2e04 100644 --- a/ko/codes/kotlin/chapter_heap/heap.kt +++ b/ko/codes/kotlin/chapter_heap/heap.kt @@ -9,58 +9,74 @@ package chapter_heap import utils.printHeap import java.util.* -fun testPush(heap: Queue, _val: Int) { - heap.offer(_val) // 힙에 원소 삽입 - print("\n힙에 원소($_val)를 삽입한 후\n") - printHeap(heap) -} - -fun testPop(heap: Queue) { - val _val = heap.poll() // 힙의 루트 원소 꺼내기 - print("\n힙의 루트 원소($_val)를 꺼낸 후\n") - printHeap(heap) -} - /* 실행 코드 */ fun main() { + // [region]{init} /* 힙 초기화 */ // 최소 힙 초기화 var minHeap = PriorityQueue() - // 최대 힙 초기화(lambda 식으로 Comparator를 수정하면 된다) val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + // [endregion]{init} println("\n다음 테스트 예제는 최대 힙이다") + // [region]{push} /* 힙에 원소 삽입 */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + maxHeap.offer(1) + maxHeap.offer(3) + maxHeap.offer(2) + maxHeap.offer(5) + maxHeap.offer(4) + // [endregion]{push} + printHeap(maxHeap) + // [region]{peek} /* 힙의 루트 원소 반환 */ - val peek = maxHeap.peek() + var peek = maxHeap.peek() // 5 + // [endregion]{peek} print("\n힙의 루트 원소 = $peek\n") + // [region]{pop_1} /* 힙의 루트 원소 꺼내기 */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 + peek = maxHeap.poll() // 5 + // [endregion]{pop_1} + println(peek) + // [region]{pop_2} + peek = maxHeap.poll() // 4 + // [endregion]{pop_2} + println(peek) + // [region]{pop_3} + peek = maxHeap.poll() // 3 + // [endregion]{pop_3} + println(peek) + // [region]{pop_4} + peek = maxHeap.poll() // 2 + // [endregion]{pop_4} + println(peek) + // [region]{pop_5} + peek = maxHeap.poll() // 1 + // [endregion]{pop_5} + println(peek) + // [region]{size} /* 힙 크기 반환 */ val size = maxHeap.size + // [endregion]{size} print("\n힙의 원소 개수 = $size\n") + // [region]{is_empty} /* 힙이 비어 있는지 판단 */ val isEmpty = maxHeap.isEmpty() + // [endregion]{is_empty} print("\n힙이 비어 있는가: $isEmpty\n") + // [region]{heapify} /* 리스트를 입력하여 힙 구성 */ // 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) + // [endregion]{heapify} println("\n리스트를 입력하여 최소 힙을 구성한 후") printHeap(minHeap) } \ No newline at end of file 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..254238ead 100644 --- a/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt +++ b/ko/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt @@ -6,12 +6,14 @@ package chapter_stack_and_queue +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ class ListNode(var _val: Int) { // 노드 값 var next: ListNode? = null // 다음 노드 참조 var prev: ListNode? = null // 이전 노드 참조 } +// [endregion]{doubly_list_node} /* 이중 연결 리스트로 구현한 덱 */ class LinkedListDeque { @@ -162,4 +164,4 @@ fun main() { /* 덱이 비어 있는지 판단 */ val isEmpty = deque.isEmpty() println("덱이 비어 있는가 = $isEmpty") -} \ No newline at end of file +} diff --git a/ko/codes/kotlin/utils/ListNode.kt b/ko/codes/kotlin/utils/ListNode.kt index 7107ae29b..0aaea29d9 100644 --- a/ko/codes/kotlin/utils/ListNode.kt +++ b/ko/codes/kotlin/utils/ListNode.kt @@ -6,9 +6,11 @@ package utils +// [region]{list_node} /* 연결 리스트 노드 */ class ListNode(var _val: Int) { - var next: ListNode? = null + var next: ListNode? = null // 다음 노드를 가리키는 참조 +// [endregion]{list_node} companion object { /* 리스트를 연결 리스트로 역직렬화 */ @@ -22,4 +24,6 @@ class ListNode(var _val: Int) { return dum.next } } -} \ No newline at end of file +// [region]{list_node_end} +} +// [endregion]{list_node_end} diff --git a/ko/codes/python/chapter_heap/heap.py b/ko/codes/python/chapter_heap/heap.py index 687c683ea..e09940933 100644 --- a/ko/codes/python/chapter_heap/heap.py +++ b/ko/codes/python/chapter_heap/heap.py @@ -13,59 +13,76 @@ from modules import print_heap import heapq -def test_push(heap: list, val: int, flag: int = 1): - heapq.heappush(heap, flag * val) # 힙에 원소 삽입 - print(f"\n원소를 힙에 삽입한 후(원소: {val})") - print_heap([flag * val for val in heap]) - - -def test_pop(heap: list, flag: int = 1): - val = flag * heapq.heappop(heap) # 힙의 루트 원소 꺼내기 - print(f"\n힙의 루트 원소를 꺼낸 후(원소: {val})") - print_heap([flag * val for val in heap]) - - """실행 코드""" if __name__ == "__main__": + # [region]{init} # 최소 힙 초기화 min_heap, flag = [], 1 # 최대 힙 초기화 max_heap, flag = [], -1 - print("\n다음 테스트 예제는 최대 힙이다") # Python의 heapq 모듈은 기본적으로 최소 힙을 구현한다 # 원소의 부호를 바꾸어 힙에 삽입하면 대소 관계가 뒤집히므로 최대 힙을 구현할 수 있다 # 이 예제에서 flag = 1은 최소 힙에, flag = -1은 최대 힙에 해당한다 + # [endregion]{init} + print("\n다음 테스트 예제는 최대 힙이다") + # [region]{push} # 힙에 원소 삽입 - test_push(max_heap, 1, flag) - test_push(max_heap, 3, flag) - test_push(max_heap, 2, flag) - test_push(max_heap, 5, flag) - test_push(max_heap, 4, flag) + 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) + # [endregion]{push} + print_heap([flag * val for val in max_heap]) + # [region]{peek} # 힙의 루트 원소 반환 - peek: int = flag * max_heap[0] + peek: int = flag * max_heap[0] # 5 + # [endregion]{peek} print(f"\n힙의 루트 원소는 {peek}이다") + # [region]{pop_1} # 힙의 루트 원소 꺼내기 - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) + # 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 + val = flag * heapq.heappop(max_heap) # 5 + # [endregion]{pop_1} + print(val) + # [region]{pop_2} + val = flag * heapq.heappop(max_heap) # 4 + # [endregion]{pop_2} + print(val) + # [region]{pop_3} + val = flag * heapq.heappop(max_heap) # 3 + # [endregion]{pop_3} + print(val) + # [region]{pop_4} + val = flag * heapq.heappop(max_heap) # 2 + # [endregion]{pop_4} + print(val) + # [region]{pop_5} + val = flag * heapq.heappop(max_heap) # 1 + # [endregion]{pop_5} + print(val) + # [region]{size} # 힙 크기 반환 size: int = len(max_heap) + # [endregion]{size} print(f"\n힙의 원소 개수는 {size}개이다") + # [region]{is_empty} # 힙이 비어 있는지 판단 is_empty: bool = not max_heap + # [endregion]{is_empty} print(f"\n힙이 비어 있는가 {is_empty}") + # [region]{heapify} # 리스트를 입력하여 힙 구성 # 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 - min_heap = [1, 3, 2, 5, 4] + min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) + # [endregion]{heapify} print("\n리스트를 입력하여 최소 힙을 구성한 후") print_heap(min_heap) 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..7246ff2cc 100644 --- a/ko/codes/python/chapter_stack_and_queue/linkedlist_deque.py +++ b/ko/codes/python/chapter_stack_and_queue/linkedlist_deque.py @@ -5,14 +5,16 @@ Author: krahets (krahets@163.com) """ +# [region]{doubly_list_node} 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 # 이전 노드 참조 +# [endregion]{doubly_list_node} class LinkedListDeque: diff --git a/ko/codes/python/modules/list_node.py b/ko/codes/python/modules/list_node.py index 8d82afa28..95f7b1f38 100644 --- a/ko/codes/python/modules/list_node.py +++ b/ko/codes/python/modules/list_node.py @@ -5,12 +5,14 @@ Author: krahets (krahets@163.com) """ +# [region]{list_node} class ListNode: """연결 리스트 노드 클래스""" def __init__(self, val: int): self.val: int = val # 노드 값 - self.next: ListNode | None = None # 다음 노드 참조 + self.next: ListNode | None = None # 다음 노드를 가리키는 참조 +# [endregion]{list_node} def list_to_linked_list(arr: list[int]) -> ListNode | None: 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..875eeb949 100644 --- a/ko/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/ko/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,9 +4,10 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{doubly_list_node} ### 이중 연결 리스트 노드 class ListNode - attr_accessor :val + attr_accessor :val # 노드 값 attr_accessor :next # 다음 노드 참조 attr_accessor :prev # 이전 노드 참조 @@ -15,6 +16,7 @@ class ListNode @val = val end end +# [endregion]{doubly_list_node} ### 이중 연결 리스트로 구현한 덱 ### class LinkedListDeque diff --git a/ko/codes/ruby/utils/list_node.rb b/ko/codes/ruby/utils/list_node.rb index f9e7b80c7..bccfa373c 100644 --- a/ko/codes/ruby/utils/list_node.rb +++ b/ko/codes/ruby/utils/list_node.rb @@ -4,6 +4,7 @@ Created Time: 2024-03-18 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{list_node} ### 연결 리스트 노드 클래스 ### class ListNode attr_accessor :val # 노드 값 @@ -14,6 +15,7 @@ class ListNode @next = next_node end end +# [endregion]{list_node} ### 리스트를 연결 리스트로 역직렬화 ### def arr_to_linked_list(arr) diff --git a/ko/codes/rust/chapter_heap/heap.rs b/ko/codes/rust/chapter_heap/heap.rs index 973a76e6a..397581453 100644 --- a/ko/codes/rust/chapter_heap/heap.rs +++ b/ko/codes/rust/chapter_heap/heap.rs @@ -6,22 +6,13 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::{cmp::Reverse, collections::BinaryHeap}; - -fn test_push_max(heap: &mut BinaryHeap, val: i32) { - heap.push(val); // 힙에 원소 삽입 - println!("\n원소 {} 삽입 후의 힙", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} - -fn test_pop_max(heap: &mut BinaryHeap) { - let val = heap.pop().unwrap(); - println!("\n루트 원소 {} 삭제 후의 힙", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} +// [endregion]{import} /* 실행 코드 */ fn main() { + // [region]{init} /* 힙 초기화 */ // 최소 힙 초기화 #[allow(unused_assignments)] @@ -29,43 +20,66 @@ fn main() { // Rust의 BinaryHeap은 최대 힙이며, 최소 힙을 만들 때는 보통 Reverse로 감싼다 // 최대 힙 초기화 let mut max_heap = BinaryHeap::new(); + // [endregion]{init} println!("\n다음 테스트 예제는 최대 힙이다"); + // [region]{push} /* 힙에 원소 삽입 */ - test_push_max(&mut max_heap, 1); - test_push_max(&mut max_heap, 3); - test_push_max(&mut max_heap, 2); - test_push_max(&mut max_heap, 5); - test_push_max(&mut max_heap, 4); + max_heap.push(1); + max_heap.push(3); + max_heap.push(2); + max_heap.push(5); + max_heap.push(4); + // [endregion]{push} + print_util::print_heap(max_heap.iter().map(|&val| val).collect()); + // [region]{peek} /* 힙의 루트 원소 반환 */ - let peek = max_heap.peek().unwrap(); + let peek = max_heap.peek().unwrap(); // 5 + // [endregion]{peek} println!("\n힙의 루트 원소: {}", peek); + // [region]{pop_1} /* 힙의 루트 원소 꺼내기 */ - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); + // 힙에서 꺼낸 원소는 내림차순 수열을 이룬다 + let peek = max_heap.pop().unwrap(); // 5 + // [endregion]{pop_1} + println!("{}", peek); + // [region]{pop_2} + let peek = max_heap.pop().unwrap(); // 4 + // [endregion]{pop_2} + println!("{}", peek); + // [region]{pop_3} + let peek = max_heap.pop().unwrap(); // 3 + // [endregion]{pop_3} + println!("{}", peek); + // [region]{pop_4} + let peek = max_heap.pop().unwrap(); // 2 + // [endregion]{pop_4} + println!("{}", peek); + // [region]{pop_5} + let peek = max_heap.pop().unwrap(); // 1 + // [endregion]{pop_5} + println!("{}", peek); + // [region]{size} /* 힙 크기 반환 */ let size = max_heap.len(); + // [endregion]{size} println!("\n힙의 원소 개수: {}", size); + // [region]{is_empty} /* 힙이 비어 있는지 판단 */ let is_empty = max_heap.is_empty(); + // [endregion]{is_empty} println!("\n힙이 비어 있는가: {}", is_empty); + // [region]{heapify} /* 리스트를 입력하여 힙 구성 */ // 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 - min_heap = BinaryHeap::from( - vec![1, 3, 2, 5, 4] - .into_iter() - .map(|val| Reverse(val)) - .collect::>>(), - ); + min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); + // [endregion]{heapify} println!("\n리스트를 입력하여 최소 힙을 구성한 후"); print_util::print_heap(min_heap.iter().map(|&val| val.0).collect()); } 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..103dcdded 100644 --- a/ko/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs +++ b/ko/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs @@ -6,9 +6,12 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::cell::RefCell; use std::rc::Rc; +// [endregion]{import} +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ pub struct ListNode { pub val: T, // 노드 값 @@ -25,6 +28,7 @@ impl ListNode { })) } } +// [endregion]{doubly_list_node} /* 이중 연결 리스트로 구현한 덱 */ #[allow(dead_code)] diff --git a/ko/codes/rust/src/include/list_node.rs b/ko/codes/rust/src/include/list_node.rs index e8966954a..8c97741b5 100644 --- a/ko/codes/rust/src/include/list_node.rs +++ b/ko/codes/rust/src/include/list_node.rs @@ -4,20 +4,26 @@ * Author: codingonion (coderonion@gmail.com), rongyi (hiarongyi@gmail.com) */ +// [region]{import_cell} use std::cell::RefCell; +// [endregion]{import_cell} use std::collections::HashMap; +// [region]{import_rc} use std::rc::Rc; +// [endregion]{import_rc} +// [region]{list_node} #[derive(Debug)] pub struct ListNode { - pub val: T, - pub next: Option>>>, + pub val: T, // 노드 값 + pub next: Option>>>, // 다음 노드 포인터 } impl ListNode { pub fn new(val: T) -> Rc>> { Rc::new(RefCell::new(ListNode { val, next: None })) } +// [endregion]{list_node} /* 배열을 역직렬화하여 연결 리스트로 변환한다 */ pub fn arr_to_linked_list(array: &[T]) -> Option>>> @@ -54,4 +60,6 @@ impl ListNode { hashmap } +// [region]{list_node_end} } +// [endregion]{list_node_end} 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 2c96872f6..a71431e73 100644 --- a/ko/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/ko/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -1,52 +1,24 @@ ```python title="" -class ListNode: - """연결 리스트 노드 클래스""" - def __init__(self, val: int): - self.val: int = val # 노드 값 - self.next: ListNode | None = None # 다음 노드를 가리키는 참조 +[file]{modules/list_node}-[region]{list_node} ``` ```cpp title="" -/* 연결 리스트 노드 구조체 */ -struct ListNode { - int val; // 노드 값 - ListNode *next; // 다음 노드를 가리키는 포인터 - ListNode(int x) : val(x), next(nullptr) {} // 생성자 -}; +[file]{utils/list_node.hpp}-[region]{list_node} ``` ```java title="" -/* 연결 리스트 노드 클래스 */ -class ListNode { - int val; // 노드 값 - ListNode next; // 다음 노드를 가리키는 참조 - ListNode(int x) { val = x; } // 생성자 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```csharp title="" -/* 연결 리스트 노드 클래스 */ -class ListNode(int x) { //생성자 - public int val = x; // 노드 값 - public ListNode? next; // 다음 노드를 가리키는 참조 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```go title="" -/* 연결 리스트 노드 구조체 */ -type ListNode struct { - Val int // 노드 값 - Next *ListNode // 다음 노드를 가리키는 포인터 -} - -// NewListNode 생성자: 새 연결 리스트 생성 -func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } -} +[file]{pkg/list_node}-[region]{list_node} ``` ```swift title="" @@ -62,84 +34,36 @@ class ListNode { ``` ```javascript title="" -/* 연결 리스트 노드 클래스 */ -class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // 노드 값 - this.next = (next === undefined ? null : next); // 다음 노드를 가리키는 참조 - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```typescript title="" -/* 연결 리스트 노드 클래스 */ -class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 노드 값 - this.next = next === undefined ? null : next; // 다음 노드를 가리키는 참조 - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```dart title="" -/* 연결 리스트 노드 클래스 */ -class ListNode { - int val; // 노드 값 - ListNode? next; // 다음 노드를 가리키는 참조 - ListNode(this.val, [this.next]); // 생성자 -} +[file]{utils/list_node}-[region]{list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; -/* 연결 리스트 노드 클래스 */ -#[derive(Debug)] -struct ListNode { - val: i32, // 노드 값 - next: Option>>, // 다음 노드를 가리키는 포인터 -} +[file]{src/include/list_node}-[region]{import_cell} +[file]{src/include/list_node}-[region]{import_rc} + +[file]{src/include/list_node}-[region]{list_node} +[file]{src/include/list_node}-[region]{list_node_end} ``` ```c title="" -/* 연결 리스트 노드 구조체 */ -typedef struct ListNode { - int val; // 노드 값 - struct ListNode *next; // 다음 노드를 가리키는 포인터 -} ListNode; - -/* 생성자 */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; -} +[file]{utils/list_node.h}-[region]{list_node} ``` ```kotlin title="" -/* 연결 리스트 노드 클래스 */ -// 생성자 -class ListNode(x: Int) { - val _val: Int = x // 노드 값 - var next: ListNode? = null // 다음 노드를 가리키는 참조 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```ruby title="" -# 연결 리스트 노드 클래스 -class ListNode - attr_accessor :val # 노드 값 - attr_accessor :next # 다음 노드를 가리키는 참조 - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end -end +[file]{utils/list_node}-[region]{list_node} ``` @@ -200,41 +124,19 @@ 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 # 선행 노드를 가리키는 참조 +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```cpp title="" -/* 이중 연결 리스트 노드 구조체 */ -struct ListNode { - int val; // 노드 값 - ListNode *next; // 후속 노드를 가리키는 포인터 - ListNode *prev; // 선행 노드를 가리키는 포인터 - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 생성자 -}; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```java title="" -/* 이중 연결 리스트 노드 클래스 */ -class ListNode { - int val; // 노드 값 - ListNode next; // 후속 노드를 가리키는 참조 - ListNode prev; // 선행 노드를 가리키는 참조 - ListNode(int x) { val = x; } // 생성자 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```csharp title="" -/* 이중 연결 리스트 노드 클래스 */ -class ListNode(int x) { // 생성자 - public int val = x; // 노드 값 - public ListNode? next; // 후속 노드를 가리키는 참조 - public ListNode? prev; // 선행 노드를 가리키는 참조 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```go title="" @@ -256,117 +158,35 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* 이중 연결 리스트 노드 클래스 */ -class ListNode { - var val: Int // 노드 값 - var next: ListNode? // 후속 노드를 가리키는 참조 - var prev: ListNode? // 선행 노드를 가리키는 참조 - - init(x: Int) { // 생성자 - val = x - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // 선행 노드를 가리키는 참조 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // 선행 노드를 가리키는 참조 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```dart title="" -/* 이중 연결 리스트 노드 클래스 */ -class ListNode { - int val; // 노드 값 - ListNode? next; // 후속 노드를 가리키는 참조 - ListNode? prev; // 선행 노드를 가리키는 참조 - ListNode(this.val, [this.next, this.prev]); // 생성자 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{import} -/* 이중 연결 리스트 노드 자료형 */ -#[derive(Debug)] -struct ListNode { - val: i32, // 노드 값 - next: Option>>, // 후속 노드를 가리키는 포인터 - prev: Option>>, // 선행 노드를 가리키는 포인터 -} - -/* 생성자 */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```c title="" -/* 이중 연결 리스트 노드 구조체 */ -typedef struct ListNode { - int val; // 노드 값 - struct ListNode *next; // 후속 노드를 가리키는 포인터 - struct ListNode *prev; // 선행 노드를 가리키는 포인터 -} ListNode; - -/* 생성자 */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```kotlin title="" -/* 이중 연결 리스트 노드 클래스 */ -// 생성자 -class ListNode(x: Int) { - val _val: Int = x // 노드 값 - var next: ListNode? = null // 후속 노드를 가리키는 참조 - var prev: ListNode? = null // 선행 노드를 가리키는 참조 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```ruby title="" -# 이중 연결 리스트 노드 클래스 -class ListNode - attr_accessor :val # 노드 값 - attr_accessor :next # 후속 노드를 가리키는 참조 - attr_accessor :prev # 선행 노드를 가리키는 참조 - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end -end +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` diff --git a/ko/codes/snippets/chapter_heap/heap.md b/ko/codes/snippets/chapter_heap/heap.md index 74a50ad81..71a419ae8 100644 --- a/ko/codes/snippets/chapter_heap/heap.md +++ b/ko/codes/snippets/chapter_heap/heap.md @@ -1,256 +1,110 @@ ```python title="heap.py" -# 최소 힙 초기화 -min_heap, flag = [], 1 -# 최대 힙 초기화 -max_heap, flag = [], -1 +[file]{heap}-[region]{init} -# Python의 heapq 모듈은 기본적으로 최소 힙을 구현한다 -# 원소의 부호를 바꾼 뒤 삽입하면 대소 관계가 뒤집히므로 최대 힙을 구현할 수 있다 -# 이 예제에서 flag = 1이면 최소 힙, flag = -1이면 최대 힙에 해당한다 +[file]{heap}-[region]{push} -# 힙에 원소 삽입 -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) +[file]{heap}-[region]{peek} -# 힙의 루트 원소 구하기 -peek: int = flag * max_heap[0] # 5 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_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 +[file]{heap}-[region]{size} -# 힙의 크기 구하기 -size: int = len(max_heap) +[file]{heap}-[region]{is_empty} -# 힙이 비어 있는지 확인 -is_empty: bool = not max_heap - -# 리스트를 입력받아 힙 구성 -min_heap: list[int] = [1, 3, 2, 5, 4] -heapq.heapify(min_heap) +[file]{heap}-[region]{heapify} ``` ```cpp title="heap.cpp" -/* 힙 초기화 */ -// 최소 힙 초기화 -priority_queue, greater> minHeap; -// 최대 힙 초기화 -priority_queue, less> maxHeap; +[file]{heap}-[region]{init} -/* 힙에 원소 삽입 */ -maxHeap.push(1); -maxHeap.push(3); -maxHeap.push(2); -maxHeap.push(5); -maxHeap.push(4); +[file]{heap}-[region]{push} -/* 힙의 루트 원소 구하기 */ -int peek = maxHeap.top(); // 5 +[file]{heap}-[region]{peek} -/* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 -maxHeap.pop(); // 5 -maxHeap.pop(); // 4 -maxHeap.pop(); // 3 -maxHeap.pop(); // 2 -maxHeap.pop(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 힙의 크기 구하기 */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* 힙이 비어 있는지 확인 */ -bool isEmpty = maxHeap.empty(); +[file]{heap}-[region]{is_empty} -/* 리스트를 입력받아 힙 구성 */ -vector input{1, 3, 2, 5, 4}; -minHeap = priority_queue, greater>(input.begin(), input.end()); +[file]{heap}-[region]{heapify} ``` ```java title="heap.java" -/* 힙 초기화 */ -// 최소 힙 초기화 -Queue minHeap = new PriorityQueue<>(); -// 최대 힙 초기화(lambda 식으로 Comparator를 수정하면 된다) -Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); +[file]{heap}-[region]{init} -/* 힙에 원소 삽입 */ -maxHeap.offer(1); -maxHeap.offer(3); -maxHeap.offer(2); -maxHeap.offer(5); -maxHeap.offer(4); +[file]{heap}-[region]{push} -/* 힙의 루트 원소 구하기 */ -int peek = maxHeap.peek(); // 5 +[file]{heap}-[region]{peek} -/* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 -peek = maxHeap.poll(); // 5 -peek = maxHeap.poll(); // 4 -peek = maxHeap.poll(); // 3 -peek = maxHeap.poll(); // 2 -peek = maxHeap.poll(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 힙의 크기 구하기 */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* 힙이 비어 있는지 확인 */ -boolean isEmpty = maxHeap.isEmpty(); +[file]{heap}-[region]{is_empty} -/* 리스트를 입력받아 힙 구성 */ -minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +[file]{heap}-[region]{heapify} ``` ```csharp title="heap.cs" -/* 힙 초기화 */ -// 최소 힙 초기화 -PriorityQueue minHeap = new(); -// 최대 힙 초기화(lambda 식으로 Comparer를 수정하면 된다) -PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); +[file]{heap}-[region]{init} -/* 힙에 원소 삽입 */ -maxHeap.Enqueue(1, 1); -maxHeap.Enqueue(3, 3); -maxHeap.Enqueue(2, 2); -maxHeap.Enqueue(5, 5); -maxHeap.Enqueue(4, 4); +[file]{heap}-[region]{push} -/* 힙의 루트 원소 구하기 */ -int peek = maxHeap.Peek();//5 +[file]{heap}-[region]{peek} -/* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 힙의 크기 구하기 */ -int size = maxHeap.Count; +[file]{heap}-[region]{size} -/* 힙이 비어 있는지 확인 */ -bool isEmpty = maxHeap.Count == 0; +[file]{heap}-[region]{is_empty} -/* 리스트를 입력받아 힙 구성 */ -minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +[file]{heap}-[region]{heapify} ``` ```go title="heap.go" -// Go에서는 heap.Interface를 구현하여 정수 최대 힙을 만들 수 있다 -// heap.Interface를 구현하려면 sort.Interface도 구현해야 한다 -type intHeap []any +[file]{heap}-[region]{int_heap} -// Push는 heap.Interface의 메서드로, 힙에 원소를 삽입한다 -func (h *intHeap) Push(x any) { - // Push와 Pop은 포인터 리시버(pointer receiver)를 매개변수로 사용한다 - // 슬라이스의 내용뿐 아니라 길이도 수정하기 때문이다. - *h = append(*h, x.(int)) -} - -// Pop은 heap.Interface의 메서드로, 힙의 루트 원소를 꺼낸다 -func (h *intHeap) Pop() any { - // 꺼낼 원소는 맨 끝에 저장되어 있다 - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last -} - -// Len은 sort.Interface의 메서드다 -func (h *intHeap) Len() int { - return len(*h) -} - -// Less는 sort.Interface의 메서드다 -func (h *intHeap) Less(i, j int) bool { - // 최소 힙을 구현하려면 부등호를 <로 바꿔야 한다 - return (*h)[i].(int) > (*h)[j].(int) -} - -// Swap은 sort.Interface의 메서드다 -func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] -} - -// Top은 힙의 루트 원소를 구한다 -func (h *intHeap) Top() any { - return (*h)[0] -} - -/* 실행 코드 */ -func TestHeap(t *testing.T) { - /* 힙 초기화 */ - // 최대 힙 초기화 - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* 힙에 원소 삽입 */ - // heap.Interface의 메서드를 호출하여 원소를 추가한다 - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* 힙의 루트 원소 구하기 */ - 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 - - /* 힙의 크기 구하기 */ - size := len(*maxHeap) - fmt.Printf("힙의 원소 수: %d\n", size) - - /* 힙이 비어 있는지 확인 */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("힙이 비어 있는가: %t\n", isEmpty) -} +[file]{heap_test}-[region]{test_heap} ``` ```swift title="heap.swift" -/* 힙 초기화 */ -// Swift의 Heap 타입은 최대 힙과 최소 힙을 모두 지원하며, swift-collections를 가져와야 한다 -var heap = Heap() +[file]{heap}-[region]{import} -/* 힙에 원소 삽입 */ -heap.insert(1) -heap.insert(3) -heap.insert(2) -heap.insert(5) -heap.insert(4) +[file]{heap}-[region]{init} -/* 힙의 루트 원소 구하기 */ -var peek = heap.max()! +[file]{heap}-[region]{push} -/* 힙의 루트 원소 꺼내기 */ -peek = heap.removeMax() // 5 -peek = heap.removeMax() // 4 -peek = heap.removeMax() // 3 -peek = heap.removeMax() // 2 -peek = heap.removeMax() // 1 +[file]{heap}-[region]{peek} -/* 힙의 크기 구하기 */ -let size = heap.count +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 힙이 비어 있는지 확인 */ -let isEmpty = heap.isEmpty +[file]{heap}-[region]{size} -/* 리스트를 입력받아 힙 구성 */ -let heap2 = Heap([1, 3, 2, 5, 4]) +[file]{heap}-[region]{is_empty} + +[file]{heap}-[region]{heapify} ``` ```javascript title="heap.js" @@ -266,41 +120,25 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +[file]{heap}-[region]{import} -/* 힙 초기화 */ -// 최소 힙 초기화 -let mut min_heap = BinaryHeap::>::new(); -// 최대 힙 초기화 -let mut max_heap = BinaryHeap::new(); +[file]{heap}-[region]{init} -/* 힙에 원소 삽입 */ -max_heap.push(1); -max_heap.push(3); -max_heap.push(2); -max_heap.push(5); -max_heap.push(4); +[file]{heap}-[region]{push} -/* 힙의 루트 원소 구하기 */ -let peek = max_heap.peek().unwrap(); // 5 +[file]{heap}-[region]{peek} -/* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 -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 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 힙의 크기 구하기 */ -let size = max_heap.len(); +[file]{heap}-[region]{size} -/* 힙이 비어 있는지 확인 */ -let is_empty = max_heap.is_empty(); +[file]{heap}-[region]{is_empty} -/* 리스트를 입력받아 힙 구성 */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +[file]{heap}-[region]{heapify} ``` ```c title="heap.c" @@ -308,38 +146,23 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse ``` ```kotlin title="heap.kt" -/* 힙 초기화 */ -// 최소 힙 초기화 -var minHeap = PriorityQueue() -// 최대 힙 초기화(lambda 식으로 Comparator를 수정하면 된다) -val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } +[file]{heap}-[region]{init} -/* 힙에 원소 삽입 */ -maxHeap.offer(1) -maxHeap.offer(3) -maxHeap.offer(2) -maxHeap.offer(5) -maxHeap.offer(4) +[file]{heap}-[region]{push} -/* 힙의 루트 원소 구하기 */ -var peek = maxHeap.peek() // 5 +[file]{heap}-[region]{peek} -/* 힙의 루트 원소 꺼내기 */ -// 꺼낸 원소들은 큰 값부터 작은 값 순서로 나열된다 -peek = maxHeap.poll() // 5 -peek = maxHeap.poll() // 4 -peek = maxHeap.poll() // 3 -peek = maxHeap.poll() // 2 -peek = maxHeap.poll() // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 힙의 크기 구하기 */ -val size = maxHeap.size +[file]{heap}-[region]{size} -/* 힙이 비어 있는지 확인 */ -val isEmpty = maxHeap.isEmpty() +[file]{heap}-[region]{is_empty} -/* 리스트를 입력받아 힙 구성 */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +[file]{heap}-[region]{heapify} ``` ```ruby title="heap.rb" diff --git a/ko/codes/swift/chapter_heap/heap.swift b/ko/codes/swift/chapter_heap/heap.swift index 7b0160918..94db97767 100644 --- a/ko/codes/swift/chapter_heap/heap.swift +++ b/ko/codes/swift/chapter_heap/heap.swift @@ -4,58 +4,76 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{import} import HeapModule +// [endregion]{import} import utils -func testPush(heap: inout Heap, val: Int) { - heap.insert(val) - print("\n힙에 원소(\(val))를 삽입한 후\n") - PrintUtil.printHeap(queue: heap.unordered) -} - -func testPop(heap: inout Heap) { - let val = heap.removeMax() - print("\n힙의 루트 원소(\(val))를 꺼낸 후\n") - PrintUtil.printHeap(queue: heap.unordered) -} - @main enum _Heap { /* 실행 코드 */ static func main() { + // [region]{init} /* 힙 초기화 */ // Swift의 Heap 타입은 최대 힙과 최소 힙을 모두 지원한다 var heap = Heap() + // [endregion]{init} + // [region]{push} /* 힙에 원소 삽입 */ - testPush(heap: &heap, val: 1) - testPush(heap: &heap, val: 3) - testPush(heap: &heap, val: 2) - testPush(heap: &heap, val: 5) - testPush(heap: &heap, val: 4) + heap.insert(1) + heap.insert(3) + heap.insert(2) + heap.insert(5) + heap.insert(4) + // [endregion]{push} + PrintUtil.printHeap(queue: heap.unordered) + // [region]{peek} /* 힙의 루트 원소 반환 */ - let peek = heap.max() + var peek = heap.max() + // [endregion]{peek} print("\n힙의 루트 원소 = \(peek!)\n") + // [region]{pop_1} /* 힙의 루트 원소 꺼내기 */ - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) + peek = heap.removeMax() // 5 + // [endregion]{pop_1} + print(peek!) + // [region]{pop_2} + peek = heap.removeMax() // 4 + // [endregion]{pop_2} + print(peek!) + // [region]{pop_3} + peek = heap.removeMax() // 3 + // [endregion]{pop_3} + print(peek!) + // [region]{pop_4} + peek = heap.removeMax() // 2 + // [endregion]{pop_4} + print(peek!) + // [region]{pop_5} + peek = heap.removeMax() // 1 + // [endregion]{pop_5} + print(peek!) + // [region]{size} /* 힙 크기 반환 */ let size = heap.count + // [endregion]{size} print("\n힙의 원소 개수 = \(size)\n") + // [region]{is_empty} /* 힙이 비어 있는지 판단 */ let isEmpty = heap.isEmpty + // [endregion]{is_empty} print("\n힙이 비어 있는가: \(isEmpty)\n") + // [region]{heapify} /* 리스트를 입력하여 힙 구성 */ // 시간 복잡도는 O(n)이며 O(nlogn)이 아니다 let heap2 = Heap([1, 3, 2, 5, 4]) + // [endregion]{heapify} print("\n리스트를 입력하여 힙을 구성한 후") PrintUtil.printHeap(queue: heap2.unordered) } 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..77da4846d 100644 --- a/ko/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift +++ b/ko/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift @@ -4,6 +4,7 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ class ListNode { var val: Int // 노드 값 @@ -14,6 +15,7 @@ class ListNode { self.val = val } } +// [endregion]{doubly_list_node} /* 이중 연결 리스트로 구현한 덱 */ class LinkedListDeque { 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..0f7f69a9e 100644 --- a/ko/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/ko/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -4,10 +4,11 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* 이중 연결 리스트 노드 */ class ListNode { - prev: ListNode; // 이전 노드 참조(포인터) - next: ListNode; // 다음 노드 참조(포인터) + prev: ListNode | null; // 이전 노드 참조(포인터) + next: ListNode | null; // 다음 노드 참조(포인터) val: number; // 노드 값 constructor(val: number) { @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* 이중 연결 리스트로 구현한 덱 */ class LinkedListDeque { diff --git a/ko/codes/typescript/modules/ListNode.ts b/ko/codes/typescript/modules/ListNode.ts index d55979d8d..20a836453 100644 --- a/ko/codes/typescript/modules/ListNode.ts +++ b/ko/codes/typescript/modules/ListNode.ts @@ -4,15 +4,17 @@ * Author: Justin (xiefahit@gmail.com) */ +// [region]{list_node} /* 연결 리스트 노드 */ 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; } } +// [endregion]{list_node} /* 배열을 역직렬화하여 연결 리스트로 변환한다 */ function arrToLinkedList(arr: number[]): ListNode | null { diff --git a/ru/codes/c/chapter_stack_and_queue/linkedlist_deque.c b/ru/codes/c/chapter_stack_and_queue/linkedlist_deque.c index e1f346d3f..c7360237e 100644 --- a/ru/codes/c/chapter_stack_and_queue/linkedlist_deque.c +++ b/ru/codes/c/chapter_stack_and_queue/linkedlist_deque.c @@ -6,6 +6,7 @@ #include "../utils/common.h" +// [region]{doubly_list_node} /* Узел двусвязного списка */ typedef struct DoublyListNode { int val; // Значение узла @@ -21,6 +22,7 @@ DoublyListNode *newDoublyListNode(int num) { new->prev = NULL; return new; } +// [endregion]{doubly_list_node} /* Деструктор */ void delDoublyListNode(DoublyListNode *node) { diff --git a/ru/codes/c/utils/list_node.h b/ru/codes/c/utils/list_node.h index 76775e419..214741a7f 100644 --- a/ru/codes/c/utils/list_node.h +++ b/ru/codes/c/utils/list_node.h @@ -11,6 +11,7 @@ extern "C" { #endif +// [region]{list_node} /* Структура узла связного списка */ typedef struct ListNode { int val; // Значение узла @@ -25,6 +26,7 @@ ListNode *newListNode(int val) { node->next = NULL; return node; } +// [endregion]{list_node} /* Десериализовать массив в связный список */ ListNode *arrToLinkedList(const int *arr, size_t size) { diff --git a/ru/codes/cpp/chapter_heap/heap.cpp b/ru/codes/cpp/chapter_heap/heap.cpp index 973018009..d2941f8b9 100644 --- a/ru/codes/cpp/chapter_heap/heap.cpp +++ b/ru/codes/cpp/chapter_heap/heap.cpp @@ -6,59 +6,75 @@ #include "../utils/common.hpp" -void testPush(priority_queue &heap, int val) { - heap.push(val); // Добавление элемента в кучу - cout << "\nПосле добавления элемента " << val << " в кучу" << endl; - printHeap(heap); -} - -void testPop(priority_queue &heap) { - int val = heap.top(); - heap.pop(); - cout << "\nПосле извлечения верхнего элемента " << val << " из кучи" << endl; - printHeap(heap); -} - /* Driver Code */ int main() { + // [region]{init} /* Инициализация кучи */ // Инициализировать минимальную кучу - // priority_queue, greater> minHeap; + priority_queue, greater> minHeap; // Инициализировать максимальную кучу priority_queue, less> maxHeap; + // [endregion]{init} cout << "\nНиже приведены тестовые примеры для max-heap" << endl; + // [region]{push} /* Добавление элемента в кучу */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.push(1); + maxHeap.push(3); + maxHeap.push(2); + maxHeap.push(5); + maxHeap.push(4); + // [endregion]{push} + printHeap(maxHeap); + // [region]{peek} /* Получение элемента с вершины кучи */ - int peek = maxHeap.top(); + int peek = maxHeap.top(); // 5 + // [endregion]{peek} cout << "\nВерхний элемент кучи = " << peek << endl; + // [region]{pop_1} /* Извлечение элемента с вершины кучи */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // Извлеченные элементы образуют последовательность по убыванию + maxHeap.pop(); // 5 + // [endregion]{pop_1} + printHeap(maxHeap); + // [region]{pop_2} + maxHeap.pop(); // 4 + // [endregion]{pop_2} + printHeap(maxHeap); + // [region]{pop_3} + maxHeap.pop(); // 3 + // [endregion]{pop_3} + printHeap(maxHeap); + // [region]{pop_4} + maxHeap.pop(); // 2 + // [endregion]{pop_4} + printHeap(maxHeap); + // [region]{pop_5} + maxHeap.pop(); // 1 + // [endregion]{pop_5} + printHeap(maxHeap); + // [region]{size} /* Получение размера кучи */ int size = maxHeap.size(); + // [endregion]{size} cout << "\nКоличество элементов в куче = " << size << endl; + // [region]{is_empty} /* Проверка, пуста ли куча */ bool isEmpty = maxHeap.empty(); + // [endregion]{is_empty} cout << "\nПуста ли куча: " << isEmpty << endl; + // [region]{heapify} /* Построить кучу по входному списку */ // Временная сложность равна O(n), а не O(nlogn) vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); + minHeap = priority_queue, greater>(input.begin(), input.end()); + // [endregion]{heapify} cout << "После построения min-heap из входного списка" << endl; printHeap(minHeap); diff --git a/ru/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp b/ru/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp index f2a40bbd6..5d42e906f 100644 --- a/ru/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp +++ b/ru/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp @@ -6,6 +6,7 @@ #include "../utils/common.hpp" +// [region]{doubly_list_node} /* Узел двусвязного списка */ struct DoublyListNode { int val; // Значение узла @@ -14,6 +15,7 @@ struct DoublyListNode { DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { } }; +// [endregion]{doubly_list_node} /* Двусторонняя очередь на основе двусвязного списка */ class LinkedListDeque { diff --git a/ru/codes/cpp/utils/list_node.hpp b/ru/codes/cpp/utils/list_node.hpp index 4cfc235ce..2e6d88709 100644 --- a/ru/codes/cpp/utils/list_node.hpp +++ b/ru/codes/cpp/utils/list_node.hpp @@ -11,13 +11,15 @@ using namespace std; +// [region]{list_node} /* Узел связного списка */ struct ListNode { - int val; - ListNode *next; + int val; // Значение узла + ListNode *next; // Указатель на узел-преемник ListNode(int x) : val(x), next(nullptr) { } }; +// [endregion]{list_node} /* Десериализовать список в связный список */ ListNode *vecToLinkedList(vector list) { diff --git a/ru/codes/csharp/chapter_heap/heap.cs b/ru/codes/csharp/chapter_heap/heap.cs index fc73cec56..7da62d8c3 100644 --- a/ru/codes/csharp/chapter_heap/heap.cs +++ b/ru/codes/csharp/chapter_heap/heap.cs @@ -7,57 +7,72 @@ namespace hello_algo.chapter_heap; public class heap { - void TestPush(PriorityQueue heap, int val) { - heap.Enqueue(val, val); // Добавление элемента в кучу - Console.WriteLine($"\nПосле добавления элемента {val} в кучу\n"); - PrintUtil.PrintHeap(heap); - } - - void TestPop(PriorityQueue heap) { - int val = heap.Dequeue(); // Извлечение элемента с вершины кучи - Console.WriteLine($"\nПосле извлечения элемента вершины кучи {val}\n"); - PrintUtil.PrintHeap(heap); - } - [Test] public void Test() { + // [region]{init} /* Инициализация кучи */ // Инициализация минимальной кучи PriorityQueue minHeap = new(); // Инициализировать максимальную кучу (достаточно изменить Comparer с помощью lambda-выражения) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + // [endregion]{init} Console.WriteLine("Ниже приведен тестовый пример для max-heap"); + // [region]{push} /* Добавление элемента в кучу */ - TestPush(maxHeap, 1); - TestPush(maxHeap, 3); - TestPush(maxHeap, 2); - TestPush(maxHeap, 5); - TestPush(maxHeap, 4); + maxHeap.Enqueue(1, 1); + maxHeap.Enqueue(3, 3); + maxHeap.Enqueue(2, 2); + maxHeap.Enqueue(5, 5); + maxHeap.Enqueue(4, 4); + // [endregion]{push} + PrintUtil.PrintHeap(maxHeap); + // [region]{peek} /* Получение элемента с вершины кучи */ - int peek = maxHeap.Peek(); + int peek = maxHeap.Peek(); // 5 + // [endregion]{peek} Console.WriteLine($"Элемент на вершине кучи = {peek}"); + // [region]{pop_1} /* Извлечение элемента с вершины кучи */ // Элементы, извлеченные из кучи, образуют последовательность от большего к меньшему - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); + peek = maxHeap.Dequeue(); // 5 + // [endregion]{pop_1} + Console.WriteLine(peek); + // [region]{pop_2} + peek = maxHeap.Dequeue(); // 4 + // [endregion]{pop_2} + Console.WriteLine(peek); + // [region]{pop_3} + peek = maxHeap.Dequeue(); // 3 + // [endregion]{pop_3} + Console.WriteLine(peek); + // [region]{pop_4} + peek = maxHeap.Dequeue(); // 2 + // [endregion]{pop_4} + Console.WriteLine(peek); + // [region]{pop_5} + peek = maxHeap.Dequeue(); // 1 + // [endregion]{pop_5} + Console.WriteLine(peek); + // [region]{size} /* Получение размера кучи */ int size = maxHeap.Count; + // [endregion]{size} Console.WriteLine($"Количество элементов в куче = {size}"); + // [region]{is_empty} /* Проверка, пуста ли куча */ bool isEmpty = maxHeap.Count == 0; + // [endregion]{is_empty} Console.WriteLine($"Пуста ли куча: {isEmpty}"); + // [region]{heapify} /* Построить кучу по входному списку */ - var list = new int[] { 1, 3, 2, 5, 4 }; - minHeap = new PriorityQueue(list.Select(x => (x, x))); + minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); + // [endregion]{heapify} Console.WriteLine("После построения min-heap из входного списка"); PrintUtil.PrintHeap(minHeap); } diff --git a/ru/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs b/ru/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs index 6322abad2..18ceef518 100644 --- a/ru/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs +++ b/ru/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs @@ -6,12 +6,14 @@ namespace hello_algo.chapter_stack_and_queue; +// [region]{doubly_list_node} /* Узел двусвязного списка */ public class ListNode(int val) { - public int val = val; // Значение узла + public int val = val; // Значение узла public ListNode? next = null; // Ссылка на узел-преемник public ListNode? prev = null; // Ссылка на узел-предшественник } +// [endregion]{doubly_list_node} /* Двусторонняя очередь на основе двусвязного списка */ public class LinkedListDeque { diff --git a/ru/codes/csharp/utils/ListNode.cs b/ru/codes/csharp/utils/ListNode.cs index 35f1b555c..e42c02bee 100644 --- a/ru/codes/csharp/utils/ListNode.cs +++ b/ru/codes/csharp/utils/ListNode.cs @@ -4,10 +4,12 @@ namespace hello_algo.utils; +// [region]{list_node} /* Узел связного списка */ public class ListNode(int x) { - public int val = x; - public ListNode? next; + public int val = x; // Значение узла + public ListNode? next; // Ссылка на следующий узел +// [endregion]{list_node} /* Десериализовать массив в связный список */ public static ListNode? ArrToLinkedList(int[] arr) { @@ -29,4 +31,6 @@ public class ListNode(int x) { } return string.Join("->", list); } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/ru/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart b/ru/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart index 23397e158..6b69d8a76 100644 --- a/ru/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart +++ b/ru/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart @@ -4,6 +4,7 @@ * Author: liuyuxin (gvenusleo@gmail.com) */ +// [region]{doubly_list_node} /* Узел двусвязного списка */ class ListNode { int val; // Значение узла @@ -12,6 +13,7 @@ class ListNode { ListNode(this.val, {this.next, this.prev}); } +// [endregion]{doubly_list_node} /* Двусторонняя очередь на основе двусвязного списка */ class LinkedListDeque { diff --git a/ru/codes/dart/utils/list_node.dart b/ru/codes/dart/utils/list_node.dart index 8425b4db5..18e01ac95 100644 --- a/ru/codes/dart/utils/list_node.dart +++ b/ru/codes/dart/utils/list_node.dart @@ -4,13 +4,15 @@ * Author: Jefferson (JeffersonHuang77@gmail.com) */ +// [region]{list_node} /* Узел связного списка */ class ListNode { - int val; - ListNode? next; + int val; // Значение узла + ListNode? next; // Ссылка на следующий узел - ListNode(this.val, [this.next]); + ListNode(this.val, [this.next]); // Конструктор } +// [endregion]{list_node} /* Десериализовать список в связный список */ ListNode? listToLinkedList(List list) { diff --git a/ru/codes/go/chapter_heap/heap.go b/ru/codes/go/chapter_heap/heap.go index b5ef628e0..079eb3129 100644 --- a/ru/codes/go/chapter_heap/heap.go +++ b/ru/codes/go/chapter_heap/heap.go @@ -4,6 +4,7 @@ package chapter_heap +// [region]{int_heap} // В Go можно построить максимальную кучу для целых чисел, реализовав heap.Interface // Для реализации heap.Interface одновременно требуется реализовать sort.Interface type intHeap []any @@ -43,3 +44,5 @@ func (h *intHeap) Swap(i, j int) { func (h *intHeap) Top() any { return (*h)[0] } + +// [endregion]{int_heap} diff --git a/ru/codes/go/chapter_heap/heap_test.go b/ru/codes/go/chapter_heap/heap_test.go index e96783a74..58b777734 100644 --- a/ru/codes/go/chapter_heap/heap_test.go +++ b/ru/codes/go/chapter_heap/heap_test.go @@ -13,42 +13,32 @@ import ( . "github.com/krahets/hello-algo/pkg" ) -func testPush(h *intHeap, val int) { - // Вызвать функции heap.Interface для добавления элемента - heap.Push(h, val) - fmt.Printf("\nПосле добавления элемента %d в кучу\n", val) - PrintHeap(*h) -} - -func testPop(h *intHeap) { - // Вызвать функции heap.Interface для удаления элемента - val := heap.Pop(h) - fmt.Printf("\nПосле извлечения элемента вершины кучи %d\n", val) - PrintHeap(*h) -} - +// [region]{test_heap} func TestHeap(t *testing.T) { /* Инициализация кучи */ // Инициализация максимальной кучи maxHeap := &intHeap{} heap.Init(maxHeap) /* Добавление элемента в кучу */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + // Вызвать функции heap.Interface для добавления элемента + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) /* Получение элемента с вершины кучи */ top := maxHeap.Top() fmt.Printf("Элемент на вершине кучи = %d\n", top) /* Извлечение элемента с вершины кучи */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // Вызвать функции heap.Interface для удаления элемента + fmt.Println(heap.Pop(maxHeap)) // 5 + fmt.Println(heap.Pop(maxHeap)) // 4 + fmt.Println(heap.Pop(maxHeap)) // 3 + fmt.Println(heap.Pop(maxHeap)) // 2 + fmt.Println(heap.Pop(maxHeap)) // 1 /* Получение размера кучи */ size := len(*maxHeap) @@ -59,6 +49,8 @@ func TestHeap(t *testing.T) { fmt.Printf("Пуста ли куча: %t\n", isEmpty) } +// [endregion]{test_heap} + func TestMyHeap(t *testing.T) { /* Инициализация кучи */ // Инициализация максимальной кучи diff --git a/ru/codes/go/pkg/list_node.go b/ru/codes/go/pkg/list_node.go index 3964b166e..ee9ca21d7 100644 --- a/ru/codes/go/pkg/list_node.go +++ b/ru/codes/go/pkg/list_node.go @@ -4,20 +4,23 @@ package pkg +// [region]{list_node} // ListNode: узел связного списка type ListNode struct { - Next *ListNode - Val int + Val int // Значение узла + Next *ListNode // Указатель на узел-преемник } // NewListNode: конструктор узла связного списка func NewListNode(v int) *ListNode { return &ListNode{ - Next: nil, Val: v, + Next: nil, } } +// [endregion]{list_node} + // ArrayToLinkedList десериализует массив в связный список func ArrayToLinkedList(arr []int) *ListNode { // dummy header of linked list diff --git a/ru/codes/java/chapter_heap/heap.java b/ru/codes/java/chapter_heap/heap.java index a20409d64..fb2ca03bb 100644 --- a/ru/codes/java/chapter_heap/heap.java +++ b/ru/codes/java/chapter_heap/heap.java @@ -10,56 +10,73 @@ import utils.*; import java.util.*; public class heap { - public static void testPush(Queue heap, int val) { - heap.offer(val); // Добавление элемента в кучу - System.out.format("\nПосле добавления элемента %d в кучу\n", val); - PrintUtil.printHeap(heap); - } - - public static void testPop(Queue heap) { - int val = heap.poll(); // Извлечение элемента с вершины кучи - System.out.format("\nПосле удаления элемента %d с вершины кучи\n", val); - PrintUtil.printHeap(heap); - } - public static void main(String[] args) { + // [region]{init} /* Инициализация кучи */ // Инициализация минимальной кучи Queue minHeap = new PriorityQueue<>(); // Инициализация максимальной кучи (достаточно изменить Comparator с помощью lambda-выражения) Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + // [endregion]{init} System.out.println("\nНиже приведен тестовый пример для max-heap"); + // [region]{push} /* Добавление элемента в кучу */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.offer(1); + maxHeap.offer(3); + maxHeap.offer(2); + maxHeap.offer(5); + maxHeap.offer(4); + // [endregion]{push} + PrintUtil.printHeap(maxHeap); + // [region]{peek} /* Получение элемента с вершины кучи */ - int peek = maxHeap.peek(); + int peek = maxHeap.peek(); // 5 + // [endregion]{peek} System.out.format("\nЭлемент на вершине кучи = %d\n", peek); + // [region]{pop_1} /* Извлечение элемента с вершины кучи */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // Извлеченные элементы образуют последовательность по убыванию + peek = maxHeap.poll(); // 5 + // [endregion]{pop_1} + System.out.println(peek); + // [region]{pop_2} + peek = maxHeap.poll(); // 4 + // [endregion]{pop_2} + System.out.println(peek); + // [region]{pop_3} + peek = maxHeap.poll(); // 3 + // [endregion]{pop_3} + System.out.println(peek); + // [region]{pop_4} + peek = maxHeap.poll(); // 2 + // [endregion]{pop_4} + System.out.println(peek); + // [region]{pop_5} + peek = maxHeap.poll(); // 1 + // [endregion]{pop_5} + System.out.println(peek); + // [region]{size} /* Получение размера кучи */ int size = maxHeap.size(); + // [endregion]{size} System.out.format("\nКоличество элементов в куче = %d\n", size); + // [region]{is_empty} /* Проверка, пуста ли куча */ boolean isEmpty = maxHeap.isEmpty(); + // [endregion]{is_empty} System.out.format("\nПуста ли куча: %b\n", isEmpty); + // [region]{heapify} /* Построить кучу по входному списку */ // Временная сложность равна O(n), а не O(nlogn) minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); + // [endregion]{heapify} System.out.println("\nПосле построения min-heap из входного списка"); PrintUtil.printHeap(minHeap); } diff --git a/ru/codes/java/chapter_stack_and_queue/linkedlist_deque.java b/ru/codes/java/chapter_stack_and_queue/linkedlist_deque.java index 300dcb30b..e631f4991 100644 --- a/ru/codes/java/chapter_stack_and_queue/linkedlist_deque.java +++ b/ru/codes/java/chapter_stack_and_queue/linkedlist_deque.java @@ -8,9 +8,10 @@ package chapter_stack_and_queue; import java.util.*; +// [region]{doubly_list_node} /* Узел двусвязного списка */ class ListNode { - int val; // Значение узла + int val; // Значение узла ListNode next; // Ссылка на узел-преемник ListNode prev; // Ссылка на узел-предшественник @@ -19,6 +20,7 @@ class ListNode { prev = next = null; } } +// [endregion]{doubly_list_node} /* Двусторонняя очередь на основе двусвязного списка */ class LinkedListDeque { diff --git a/ru/codes/java/utils/ListNode.java b/ru/codes/java/utils/ListNode.java index b960fdf8f..ceb636a4c 100644 --- a/ru/codes/java/utils/ListNode.java +++ b/ru/codes/java/utils/ListNode.java @@ -6,14 +6,16 @@ package utils; +// [region]{list_node} /* Узел связного списка */ public class ListNode { - public int val; - public ListNode next; + public int val; // Значение узла + public ListNode next; // Ссылка на следующий узел public ListNode(int x) { val = x; } +// [endregion]{list_node} /* Десериализовать список в связный список */ public static ListNode arrToLinkedList(int[] arr) { @@ -25,4 +27,6 @@ public class ListNode { } return dum.next; } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/ru/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js b/ru/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js index d5ce5adae..429aa6994 100644 --- a/ru/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js +++ b/ru/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js @@ -4,6 +4,7 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* Узел двусвязного списка */ class ListNode { prev; // Ссылка на узел-предшественник (указатель) @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* Двусторонняя очередь на основе двусвязного списка */ class LinkedListDeque { diff --git a/ru/codes/javascript/modules/ListNode.js b/ru/codes/javascript/modules/ListNode.js index 5944e9d2e..b4ff628a4 100644 --- a/ru/codes/javascript/modules/ListNode.js +++ b/ru/codes/javascript/modules/ListNode.js @@ -4,6 +4,7 @@ * Author: IsChristina (christinaxia77@foxmail.com) */ +// [region]{list_node} /* Узел связного списка */ class ListNode { val; // Значение узла @@ -13,6 +14,7 @@ class ListNode { this.next = next === undefined ? null : next; } } +// [endregion]{list_node} /* Десериализовать список в связный список */ function arrToLinkedList(arr) { diff --git a/ru/codes/kotlin/chapter_heap/heap.kt b/ru/codes/kotlin/chapter_heap/heap.kt index 418b63912..947b67f31 100644 --- a/ru/codes/kotlin/chapter_heap/heap.kt +++ b/ru/codes/kotlin/chapter_heap/heap.kt @@ -9,58 +9,74 @@ package chapter_heap import utils.printHeap import java.util.* -fun testPush(heap: Queue, _val: Int) { - heap.offer(_val) // Добавление элемента в кучу - print("\nПосле добавления элемента $_val в кучу\n") - printHeap(heap) -} - -fun testPop(heap: Queue) { - val _val = heap.poll() // Извлечение элемента с вершины кучи - print("\nПосле извлечения элемента вершины кучи $_val\n") - printHeap(heap) -} - /* Driver Code */ fun main() { + // [region]{init} /* Инициализация кучи */ // Инициализация минимальной кучи var minHeap = PriorityQueue() - // Инициализация максимальной кучи (достаточно изменить Comparator с помощью lambda-выражения) val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + // [endregion]{init} println("\nНиже приведен тестовый пример для max-heap") + // [region]{push} /* Добавление элемента в кучу */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + maxHeap.offer(1) + maxHeap.offer(3) + maxHeap.offer(2) + maxHeap.offer(5) + maxHeap.offer(4) + // [endregion]{push} + printHeap(maxHeap) + // [region]{peek} /* Получение элемента с вершины кучи */ - val peek = maxHeap.peek() + var peek = maxHeap.peek() // 5 + // [endregion]{peek} print("\nЭлемент на вершине кучи = $peek\n") + // [region]{pop_1} /* Извлечение элемента с вершины кучи */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // Извлеченные элементы образуют последовательность по убыванию + peek = maxHeap.poll() // 5 + // [endregion]{pop_1} + println(peek) + // [region]{pop_2} + peek = maxHeap.poll() // 4 + // [endregion]{pop_2} + println(peek) + // [region]{pop_3} + peek = maxHeap.poll() // 3 + // [endregion]{pop_3} + println(peek) + // [region]{pop_4} + peek = maxHeap.poll() // 2 + // [endregion]{pop_4} + println(peek) + // [region]{pop_5} + peek = maxHeap.poll() // 1 + // [endregion]{pop_5} + println(peek) + // [region]{size} /* Получение размера кучи */ val size = maxHeap.size + // [endregion]{size} print("\nКоличество элементов в куче = $size\n") + // [region]{is_empty} /* Проверка, пуста ли куча */ val isEmpty = maxHeap.isEmpty() + // [endregion]{is_empty} print("\nПуста ли куча: $isEmpty\n") + // [region]{heapify} /* Построить кучу по входному списку */ // Временная сложность равна O(n), а не O(nlogn) minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) + // [endregion]{heapify} println("\nПосле построения min-heap из входного списка") printHeap(minHeap) } \ No newline at end of file diff --git a/ru/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt b/ru/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt index e9f6dcb3f..b86673308 100644 --- a/ru/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt +++ b/ru/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt @@ -6,12 +6,14 @@ package chapter_stack_and_queue +// [region]{doubly_list_node} /* Узел двусвязного списка */ class ListNode(var _val: Int) { // Значение узла var next: ListNode? = null // Ссылка на узел-преемник var prev: ListNode? = null // Ссылка на узел-предшественник } +// [endregion]{doubly_list_node} /* Двусторонняя очередь на основе двусвязного списка */ class LinkedListDeque { @@ -162,4 +164,4 @@ fun main() { /* Проверка, пуста ли двусторонняя очередь */ val isEmpty = deque.isEmpty() println("Пуста ли двусторонняя очередь = $isEmpty") -} \ No newline at end of file +} diff --git a/ru/codes/kotlin/utils/ListNode.kt b/ru/codes/kotlin/utils/ListNode.kt index c19397faf..9be585ffb 100644 --- a/ru/codes/kotlin/utils/ListNode.kt +++ b/ru/codes/kotlin/utils/ListNode.kt @@ -6,9 +6,11 @@ package utils +// [region]{list_node} /* Узел связного списка */ class ListNode(var _val: Int) { - var next: ListNode? = null + var next: ListNode? = null // Ссылка на следующий узел +// [endregion]{list_node} companion object { /* Десериализовать список в связный список */ @@ -22,4 +24,6 @@ class ListNode(var _val: Int) { return dum.next } } -} \ No newline at end of file +// [region]{list_node_end} +} +// [endregion]{list_node_end} diff --git a/ru/codes/python/chapter_heap/heap.py b/ru/codes/python/chapter_heap/heap.py index bf3a1d2f2..60e846a06 100644 --- a/ru/codes/python/chapter_heap/heap.py +++ b/ru/codes/python/chapter_heap/heap.py @@ -13,59 +13,76 @@ from modules import print_heap import heapq -def test_push(heap: list, val: int, flag: int = 1): - heapq.heappush(heap, flag * val) # Добавление элемента в кучу - print(f"\nПосле добавления элемента {val} в кучу") - print_heap([flag * val for val in heap]) - - -def test_pop(heap: list, flag: int = 1): - val = flag * heapq.heappop(heap) # Извлечение элемента с вершины кучи - print(f"\nПосле извлечения элемента вершины кучи {val}") - print_heap([flag * val for val in heap]) - - """Driver Code""" if __name__ == "__main__": + # [region]{init} # Инициализация минимальной кучи min_heap, flag = [], 1 # Инициализация максимальной кучи max_heap, flag = [], -1 - print("\nНиже приведен тестовый пример для max-heap") # Модуль heapq в Python по умолчанию реализует минимальную кучу # Можно помещать в кучу отрицательные элементы, чтобы инвертировать отношение порядка и таким образом реализовать максимальную кучу # В этом примере flag = 1 соответствует минимальной куче, а flag = -1 — максимальной куче + # [endregion]{init} + print("\nНиже приведен тестовый пример для max-heap") + # [region]{push} # Добавление элемента в кучу - test_push(max_heap, 1, flag) - test_push(max_heap, 3, flag) - test_push(max_heap, 2, flag) - test_push(max_heap, 5, flag) - test_push(max_heap, 4, flag) + 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) + # [endregion]{push} + print_heap([flag * val for val in max_heap]) + # [region]{peek} # Получение элемента с вершины кучи - peek: int = flag * max_heap[0] + peek: int = flag * max_heap[0] # 5 + # [endregion]{peek} print(f"\nЭлемент на вершине кучи = {peek}") + # [region]{pop_1} # Извлечение элемента с вершины кучи - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) + # Извлеченные элементы образуют последовательность по убыванию + val = flag * heapq.heappop(max_heap) # 5 + # [endregion]{pop_1} + print(val) + # [region]{pop_2} + val = flag * heapq.heappop(max_heap) # 4 + # [endregion]{pop_2} + print(val) + # [region]{pop_3} + val = flag * heapq.heappop(max_heap) # 3 + # [endregion]{pop_3} + print(val) + # [region]{pop_4} + val = flag * heapq.heappop(max_heap) # 2 + # [endregion]{pop_4} + print(val) + # [region]{pop_5} + val = flag * heapq.heappop(max_heap) # 1 + # [endregion]{pop_5} + print(val) + # [region]{size} # Получение размера кучи size: int = len(max_heap) + # [endregion]{size} print(f"\nКоличество элементов в куче = {size}") + # [region]{is_empty} # Проверка, пуста ли куча is_empty: bool = not max_heap + # [endregion]{is_empty} print(f"\nПуста ли куча: {is_empty}") + # [region]{heapify} # Создать кучу по входному списку # Временная сложность равна O(n), а не O(nlogn) - min_heap = [1, 3, 2, 5, 4] + min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) + # [endregion]{heapify} print("\nПосле построения min-heap из входного списка") print_heap(min_heap) diff --git a/ru/codes/python/chapter_stack_and_queue/linkedlist_deque.py b/ru/codes/python/chapter_stack_and_queue/linkedlist_deque.py index 3c8108eea..bd5187d60 100644 --- a/ru/codes/python/chapter_stack_and_queue/linkedlist_deque.py +++ b/ru/codes/python/chapter_stack_and_queue/linkedlist_deque.py @@ -5,14 +5,16 @@ Author: krahets (krahets@163.com) """ +# [region]{doubly_list_node} 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 # Ссылка на узел-предшественник +# [endregion]{doubly_list_node} class LinkedListDeque: diff --git a/ru/codes/python/modules/list_node.py b/ru/codes/python/modules/list_node.py index 252e5b250..906b55ba0 100644 --- a/ru/codes/python/modules/list_node.py +++ b/ru/codes/python/modules/list_node.py @@ -5,12 +5,14 @@ Author: krahets (krahets@163.com) """ +# [region]{list_node} class ListNode: """Класс узла связного списка""" def __init__(self, val: int): self.val: int = val # Значение узла - self.next: ListNode | None = None # Ссылка на узел-преемник + self.next: ListNode | None = None # Ссылка на следующий узел +# [endregion]{list_node} def list_to_linked_list(arr: list[int]) -> ListNode | None: 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..3609d754d 100644 --- a/ru/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb +++ b/ru/codes/ruby/chapter_stack_and_queue/linkedlist_deque.rb @@ -4,9 +4,10 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{doubly_list_node} ### Узел двусвязного списка class ListNode - attr_accessor :val + attr_accessor :val # Значение узла attr_accessor :next # Ссылка на узел-преемник attr_accessor :prev # Ссылка на узел-предшественник @@ -15,6 +16,7 @@ class ListNode @val = val end end +# [endregion]{doubly_list_node} ### Двусторонняя очередь на основе двусвязного списка ### class LinkedListDeque diff --git a/ru/codes/ruby/utils/list_node.rb b/ru/codes/ruby/utils/list_node.rb index 3cceb6afe..670ebf59b 100644 --- a/ru/codes/ruby/utils/list_node.rb +++ b/ru/codes/ruby/utils/list_node.rb @@ -4,6 +4,7 @@ Created Time: 2024-03-18 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{list_node} ### Класс узла связного списка ### class ListNode attr_accessor :val # Значение узла @@ -14,6 +15,7 @@ class ListNode @next = next_node end end +# [endregion]{list_node} ### Десериализация списка в связный список ### def arr_to_linked_list(arr) diff --git a/ru/codes/rust/chapter_heap/heap.rs b/ru/codes/rust/chapter_heap/heap.rs index ec4ed3ca3..b72ad6489 100644 --- a/ru/codes/rust/chapter_heap/heap.rs +++ b/ru/codes/rust/chapter_heap/heap.rs @@ -6,22 +6,13 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::{cmp::Reverse, collections::BinaryHeap}; - -fn test_push_max(heap: &mut BinaryHeap, val: i32) { - heap.push(val); // Добавление элемента в кучу - println!("\nПосле добавления элемента {} в кучу", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} - -fn test_pop_max(heap: &mut BinaryHeap) { - let val = heap.pop().unwrap(); - println!("\nПосле извлечения элемента вершины кучи {}", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} +// [endregion]{import} /* Driver Code */ fn main() { + // [region]{init} /* Инициализация кучи */ // Инициализация минимальной кучи #[allow(unused_assignments)] @@ -29,43 +20,66 @@ fn main() { // BinaryHeap в Rust является максимальной кучей; для минимальной кучи обычно используют оболочку Reverse // Инициализировать максимальную кучу let mut max_heap = BinaryHeap::new(); + // [endregion]{init} println!("\nНиже приведен тестовый пример для max-heap"); + // [region]{push} /* Добавление элемента в кучу */ - test_push_max(&mut max_heap, 1); - test_push_max(&mut max_heap, 3); - test_push_max(&mut max_heap, 2); - test_push_max(&mut max_heap, 5); - test_push_max(&mut max_heap, 4); + max_heap.push(1); + max_heap.push(3); + max_heap.push(2); + max_heap.push(5); + max_heap.push(4); + // [endregion]{push} + print_util::print_heap(max_heap.iter().map(|&val| val).collect()); + // [region]{peek} /* Получение элемента с вершины кучи */ - let peek = max_heap.peek().unwrap(); + let peek = max_heap.peek().unwrap(); // 5 + // [endregion]{peek} println!("\nЭлемент на вершине кучи = {}", peek); + // [region]{pop_1} /* Извлечение элемента с вершины кучи */ - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); + // Извлеченные элементы образуют последовательность по убыванию + let peek = max_heap.pop().unwrap(); // 5 + // [endregion]{pop_1} + println!("{}", peek); + // [region]{pop_2} + let peek = max_heap.pop().unwrap(); // 4 + // [endregion]{pop_2} + println!("{}", peek); + // [region]{pop_3} + let peek = max_heap.pop().unwrap(); // 3 + // [endregion]{pop_3} + println!("{}", peek); + // [region]{pop_4} + let peek = max_heap.pop().unwrap(); // 2 + // [endregion]{pop_4} + println!("{}", peek); + // [region]{pop_5} + let peek = max_heap.pop().unwrap(); // 1 + // [endregion]{pop_5} + println!("{}", peek); + // [region]{size} /* Получение размера кучи */ let size = max_heap.len(); + // [endregion]{size} println!("\nКоличество элементов в куче = {}", size); + // [region]{is_empty} /* Проверка, пуста ли куча */ let is_empty = max_heap.is_empty(); + // [endregion]{is_empty} println!("\nПуста ли куча: {}", is_empty); + // [region]{heapify} /* Построить кучу по входному списку */ // Временная сложность равна O(n), а не O(nlogn) - min_heap = BinaryHeap::from( - vec![1, 3, 2, 5, 4] - .into_iter() - .map(|val| Reverse(val)) - .collect::>>(), - ); + min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); + // [endregion]{heapify} println!("\nПосле построения min-heap из входного списка"); print_util::print_heap(min_heap.iter().map(|&val| val.0).collect()); } diff --git a/ru/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs b/ru/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs index c8a745b46..0eed68fd8 100644 --- a/ru/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs +++ b/ru/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs @@ -6,9 +6,12 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::cell::RefCell; use std::rc::Rc; +// [endregion]{import} +// [region]{doubly_list_node} /* Узел двусвязного списка */ pub struct ListNode { pub val: T, // Значение узла @@ -25,6 +28,7 @@ impl ListNode { })) } } +// [endregion]{doubly_list_node} /* Двусторонняя очередь на основе двусвязного списка */ #[allow(dead_code)] diff --git a/ru/codes/rust/src/include/list_node.rs b/ru/codes/rust/src/include/list_node.rs index edb6d1ef6..237059690 100644 --- a/ru/codes/rust/src/include/list_node.rs +++ b/ru/codes/rust/src/include/list_node.rs @@ -4,20 +4,26 @@ * Author: codingonion (coderonion@gmail.com), rongyi (hiarongyi@gmail.com) */ +// [region]{import_cell} use std::cell::RefCell; +// [endregion]{import_cell} use std::collections::HashMap; +// [region]{import_rc} use std::rc::Rc; +// [endregion]{import_rc} +// [region]{list_node} #[derive(Debug)] pub struct ListNode { - pub val: T, - pub next: Option>>>, + pub val: T, // Значение узла + pub next: Option>>>, // Указатель на узел-преемник } impl ListNode { pub fn new(val: T) -> Rc>> { Rc::new(RefCell::new(ListNode { val, next: None })) } +// [endregion]{list_node} /* Десериализовать массив в связный список */ pub fn arr_to_linked_list(array: &[T]) -> Option>>> @@ -54,4 +60,6 @@ impl ListNode { hashmap } +// [region]{list_node_end} } +// [endregion]{list_node_end} 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 9aa5dbb6e..882152565 100644 --- a/ru/codes/snippets/chapter_array_and_linkedlist/linked_list.md +++ b/ru/codes/snippets/chapter_array_and_linkedlist/linked_list.md @@ -1,52 +1,24 @@ ```python title="" -class ListNode: - """Класс узла связного списка""" - def __init__(self, val: int): - self.val: int = val # Значение узла - self.next: ListNode | None = None # Ссылка на следующий узел +[file]{modules/list_node}-[region]{list_node} ``` ```cpp title="" -/* Структура узла связного списка */ -struct ListNode { - int val; // Значение узла - ListNode *next; // Указатель на следующий узел - ListNode(int x) : val(x), next(nullptr) {} // Конструктор -}; +[file]{utils/list_node.hpp}-[region]{list_node} ``` ```java title="" -/* Класс узла связного списка */ -class ListNode { - int val; // Значение узла - ListNode next; // Ссылка на следующий узел - ListNode(int x) { val = x; } // Конструктор -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```csharp title="" -/* Класс узла связного списка */ -class ListNode(int x) { // Конструктор - public int val = x; // Значение узла - public ListNode? next; // Ссылка на следующий узел -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```go title="" -/* Структура узла связного списка */ -type ListNode struct { - Val int // Значение узла - Next *ListNode // Указатель на следующий узел -} - -// NewListNode — функция-конструктор, создающая новый связный список. -func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } -} +[file]{pkg/list_node}-[region]{list_node} ``` ```swift title="" @@ -62,84 +34,36 @@ class ListNode { ``` ```javascript title="" -/* Класс узла связного списка */ -class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // Значение узла - this.next = (next === undefined ? null : next); // Ссылка на следующий узел - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```typescript title="" -/* Класс узла связного списка */ -class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // Значение узла - this.next = next === undefined ? null : next; // Ссылка на следующий узел - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```dart title="" -/* Класс узла связного списка */ -class ListNode { - int val; // Значение узла - ListNode? next; // Ссылка на следующий узел - ListNode(this.val, [this.next]); // Конструктор -} +[file]{utils/list_node}-[region]{list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; -/* Класс узла связного списка */ -#[derive(Debug)] -struct ListNode { - val: i32, // Значение узла - next: Option>>, // Указатель на следующий узел -} +[file]{src/include/list_node}-[region]{import_cell} +[file]{src/include/list_node}-[region]{import_rc} + +[file]{src/include/list_node}-[region]{list_node} +[file]{src/include/list_node}-[region]{list_node_end} ``` ```c title="" -/* Структура узла связного списка */ -typedef struct ListNode { - int val; // Значение узла - struct ListNode *next; // Указатель на следующий узел -} ListNode; - -/* Конструктор */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; -} +[file]{utils/list_node.h}-[region]{list_node} ``` ```kotlin title="" -/* Класс узла связного списка */ -// Конструктор -class ListNode(x: Int) { - val _val: Int = x // Значение узла - var next: ListNode? = null // Ссылка на следующий узел -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```ruby title="" -# Класс узла связного списка -class ListNode - attr_accessor :val # Значение узла - attr_accessor :next # Ссылка на следующий узел - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end -end +[file]{utils/list_node}-[region]{list_node} ``` @@ -200,41 +124,19 @@ 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 # Ссылка на предыдущий узел +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```cpp title="" -/* Структура узла двусвязного списка */ -struct ListNode { - int val; // Значение узла - ListNode *next; // Указатель на следующий узел - ListNode *prev; // Указатель на предыдущий узел - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // Конструктор -}; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```java title="" -/* Класс узла двусвязного списка */ -class ListNode { - int val; // Значение узла - ListNode next; // Ссылка на следующий узел - ListNode prev; // Ссылка на предыдущий узел - ListNode(int x) { val = x; } // Конструктор -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```csharp title="" -/* Класс узла двусвязного списка */ -class ListNode(int x) { // Конструктор - public int val = x; // Значение узла - public ListNode? next; // Ссылка на следующий узел - public ListNode? prev; // Ссылка на предыдущий узел -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```go title="" @@ -256,117 +158,35 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* Класс узла двусвязного списка */ -class ListNode { - var val: Int // Значение узла - var next: ListNode? // Ссылка на следующий узел - var prev: ListNode? // Ссылка на предыдущий узел - - init(x: Int) { // Конструктор - val = x - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // Ссылка на предыдущий узел - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // Ссылка на предыдущий узел - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```dart title="" -/* Класс узла двусвязного списка */ -class ListNode { - int val; // Значение узла - ListNode? next; // Ссылка на следующий узел - ListNode? prev; // Ссылка на предыдущий узел - ListNode(this.val, [this.next, this.prev]); // Конструктор -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{import} -/* Тип узла двусвязного списка */ -#[derive(Debug)] -struct ListNode { - val: i32, // Значение узла - next: Option>>, // Указатель на следующий узел - prev: Option>>, // Указатель на предыдущий узел -} - -/* Конструктор */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```c title="" -/* Структура узла двусвязного списка */ -typedef struct ListNode { - int val; // Значение узла - struct ListNode *next; // Указатель на следующий узел - struct ListNode *prev; // Указатель на предыдущий узел -} ListNode; - -/* Конструктор */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```kotlin title="" -/* Класс узла двусвязного списка */ -// Конструктор -class ListNode(x: Int) { - val _val: Int = x // Значение узла - var next: ListNode? = null // Ссылка на следующий узел - var prev: ListNode? = null // Ссылка на предыдущий узел -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```ruby title="" -# Класс узла двусвязного списка -class ListNode - attr_accessor :val # Значение узла - attr_accessor :next # Ссылка на следующий узел - attr_accessor :prev # Ссылка на предыдущий узел - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end -end +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` diff --git a/ru/codes/snippets/chapter_heap/heap.md b/ru/codes/snippets/chapter_heap/heap.md index 37f1ae32e..c5b60cc31 100644 --- a/ru/codes/snippets/chapter_heap/heap.md +++ b/ru/codes/snippets/chapter_heap/heap.md @@ -1,256 +1,110 @@ ```python title="heap.py" -# Инициализация минимальной кучи -min_heap, flag = [], 1 -# Инициализация максимальной кучи -max_heap, flag = [], -1 +[file]{heap}-[region]{init} -# Модуль heapq в Python по умолчанию реализует минимальную кучу -# Если инвертировать знак элемента перед добавлением, то отношение порядка перевернется и так реализуется максимальная куча -# В этом примере flag = 1 соответствует минимальной куче, а flag = -1 - максимальной +[file]{heap}-[region]{push} -# Добавление элементов в кучу -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) +[file]{heap}-[region]{peek} -# Получение элемента на вершине кучи -peek: int = flag * max_heap[0] # 5 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_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 +[file]{heap}-[region]{size} -# Получение размера кучи -size: int = len(max_heap) +[file]{heap}-[region]{is_empty} -# Проверка, пуста ли куча -is_empty: bool = not max_heap - -# Построение кучи из входного списка -min_heap: list[int] = [1, 3, 2, 5, 4] -heapq.heapify(min_heap) +[file]{heap}-[region]{heapify} ``` ```cpp title="heap.cpp" -/* Инициализация кучи */ -// Инициализация минимальной кучи -priority_queue, greater> minHeap; -// Инициализация максимальной кучи -priority_queue, less> maxHeap; +[file]{heap}-[region]{init} -/* Добавление элементов в кучу */ -maxHeap.push(1); -maxHeap.push(3); -maxHeap.push(2); -maxHeap.push(5); -maxHeap.push(4); +[file]{heap}-[region]{push} -/* Получение элемента на вершине кучи */ -int peek = maxHeap.top(); // 5 +[file]{heap}-[region]{peek} -/* Извлечение элемента с вершины кучи */ -// Извлеченные элементы образуют последовательность по убыванию -maxHeap.pop(); // 5 -maxHeap.pop(); // 4 -maxHeap.pop(); // 3 -maxHeap.pop(); // 2 -maxHeap.pop(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Получение размера кучи */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* Проверка, пуста ли куча */ -bool isEmpty = maxHeap.empty(); +[file]{heap}-[region]{is_empty} -/* Построение кучи из входного списка */ -vector input{1, 3, 2, 5, 4}; -minHeap = priority_queue, greater>(input.begin(), input.end()); +[file]{heap}-[region]{heapify} ``` ```java title="heap.java" -/* Инициализация кучи */ -// Инициализация минимальной кучи -Queue minHeap = new PriorityQueue<>(); -// Инициализация максимальной кучи (достаточно изменить Comparator через lambda) -Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); +[file]{heap}-[region]{init} -/* Добавление элементов в кучу */ -maxHeap.offer(1); -maxHeap.offer(3); -maxHeap.offer(2); -maxHeap.offer(5); -maxHeap.offer(4); +[file]{heap}-[region]{push} -/* Получение элемента на вершине кучи */ -int peek = maxHeap.peek(); // 5 +[file]{heap}-[region]{peek} -/* Извлечение элемента с вершины кучи */ -// Извлеченные элементы образуют последовательность по убыванию -peek = maxHeap.poll(); // 5 -peek = maxHeap.poll(); // 4 -peek = maxHeap.poll(); // 3 -peek = maxHeap.poll(); // 2 -peek = maxHeap.poll(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Получение размера кучи */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* Проверка, пуста ли куча */ -boolean isEmpty = maxHeap.isEmpty(); +[file]{heap}-[region]{is_empty} -/* Построение кучи из входного списка */ -minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +[file]{heap}-[region]{heapify} ``` ```csharp title="heap.cs" -/* Инициализация кучи */ -// Инициализация минимальной кучи -PriorityQueue minHeap = new(); -// Инициализация максимальной кучи (достаточно изменить Comparer через lambda) -PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); +[file]{heap}-[region]{init} -/* Добавление элементов в кучу */ -maxHeap.Enqueue(1, 1); -maxHeap.Enqueue(3, 3); -maxHeap.Enqueue(2, 2); -maxHeap.Enqueue(5, 5); -maxHeap.Enqueue(4, 4); +[file]{heap}-[region]{push} -/* Получение элемента на вершине кучи */ -int peek = maxHeap.Peek();//5 +[file]{heap}-[region]{peek} -/* Извлечение элемента с вершины кучи */ -// Извлеченные элементы образуют последовательность по убыванию -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Получение размера кучи */ -int size = maxHeap.Count; +[file]{heap}-[region]{size} -/* Проверка, пуста ли куча */ -bool isEmpty = maxHeap.Count == 0; +[file]{heap}-[region]{is_empty} -/* Построение кучи из входного списка */ -minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +[file]{heap}-[region]{heapify} ``` ```go title="heap.go" -// В Go можно построить целочисленную максимальную кучу, реализовав heap.Interface -// Для реализации heap.Interface также нужно реализовать sort.Interface -type intHeap []any +[file]{heap}-[region]{int_heap} -// Метод Push из heap.Interface, реализует добавление элемента в кучу -func (h *intHeap) Push(x any) { - // Push и Pop используют pointer receiver - // Потому что они не только изменяют содержимое среза, но и его длину - *h = append(*h, x.(int)) -} - -// Метод Pop из heap.Interface, реализует извлечение элемента с вершины кучи -func (h *intHeap) Pop() any { - // Извлекаемый элемент хранится в конце - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last -} - -// Метод Len из sort.Interface -func (h *intHeap) Len() int { - return len(*h) -} - -// Метод Less из sort.Interface -func (h *intHeap) Less(i, j int) bool { - // Для минимальной кучи здесь нужно заменить сравнение на < - return (*h)[i].(int) > (*h)[j].(int) -} - -// Метод Swap из sort.Interface -func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] -} - -// Top получает элемент на вершине кучи -func (h *intHeap) Top() any { - return (*h)[0] -} - -/* Driver Code */ -func TestHeap(t *testing.T) { - /* Инициализация кучи */ - // Инициализация максимальной кучи - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* Добавление элементов в кучу */ - // Вызываем методы heap.Interface для добавления элементов - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* Получение элемента на вершине кучи */ - 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 - - /* Получение размера кучи */ - size := len(*maxHeap) - fmt.Printf("Число элементов в куче: %d\n", size) - - /* Проверка, пуста ли куча */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("Пуста ли куча: %t\n", isEmpty) -} +[file]{heap_test}-[region]{test_heap} ``` ```swift title="heap.swift" -/* Инициализация кучи */ -// Тип Heap в Swift поддерживает и max-heap, и min-heap, но требует swift-collections -var heap = Heap() +[file]{heap}-[region]{import} -/* Добавление элементов в кучу */ -heap.insert(1) -heap.insert(3) -heap.insert(2) -heap.insert(5) -heap.insert(4) +[file]{heap}-[region]{init} -/* Получение элемента на вершине кучи */ -var peek = heap.max()! +[file]{heap}-[region]{push} -/* Извлечение элемента с вершины кучи */ -peek = heap.removeMax() // 5 -peek = heap.removeMax() // 4 -peek = heap.removeMax() // 3 -peek = heap.removeMax() // 2 -peek = heap.removeMax() // 1 +[file]{heap}-[region]{peek} -/* Получение размера кучи */ -let size = heap.count +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Проверка, пуста ли куча */ -let isEmpty = heap.isEmpty +[file]{heap}-[region]{size} -/* Построение кучи из входного списка */ -let heap2 = Heap([1, 3, 2, 5, 4]) +[file]{heap}-[region]{is_empty} + +[file]{heap}-[region]{heapify} ``` ```javascript title="heap.js" @@ -266,41 +120,25 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +[file]{heap}-[region]{import} -/* Инициализация кучи */ -// Инициализация минимальной кучи -let mut min_heap = BinaryHeap::>::new(); -// Инициализация максимальной кучи -let mut max_heap = BinaryHeap::new(); +[file]{heap}-[region]{init} -/* Добавление элементов в кучу */ -max_heap.push(1); -max_heap.push(3); -max_heap.push(2); -max_heap.push(5); -max_heap.push(4); +[file]{heap}-[region]{push} -/* Получение элемента на вершине кучи */ -let peek = max_heap.peek().unwrap(); // 5 +[file]{heap}-[region]{peek} -/* Извлечение элемента с вершины кучи */ -// Извлеченные элементы образуют последовательность по убыванию -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 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Получение размера кучи */ -let size = max_heap.len(); +[file]{heap}-[region]{size} -/* Проверка, пуста ли куча */ -let is_empty = max_heap.is_empty(); +[file]{heap}-[region]{is_empty} -/* Построение кучи из входного списка */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +[file]{heap}-[region]{heapify} ``` ```c title="heap.c" @@ -308,38 +146,23 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse ``` ```kotlin title="heap.kt" -/* Инициализация кучи */ -// Инициализация минимальной кучи -var minHeap = PriorityQueue() -// Инициализация максимальной кучи (достаточно изменить Comparator через lambda) -val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } +[file]{heap}-[region]{init} -/* Добавление элементов в кучу */ -maxHeap.offer(1) -maxHeap.offer(3) -maxHeap.offer(2) -maxHeap.offer(5) -maxHeap.offer(4) +[file]{heap}-[region]{push} -/* Получение элемента на вершине кучи */ -var peek = maxHeap.peek() // 5 +[file]{heap}-[region]{peek} -/* Извлечение элемента с вершины кучи */ -// Извлеченные элементы образуют последовательность по убыванию -peek = maxHeap.poll() // 5 -peek = maxHeap.poll() // 4 -peek = maxHeap.poll() // 3 -peek = maxHeap.poll() // 2 -peek = maxHeap.poll() // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* Получение размера кучи */ -val size = maxHeap.size +[file]{heap}-[region]{size} -/* Проверка, пуста ли куча */ -val isEmpty = maxHeap.isEmpty() +[file]{heap}-[region]{is_empty} -/* Построение кучи из входного списка */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +[file]{heap}-[region]{heapify} ``` ```ruby title="heap.rb" diff --git a/ru/codes/swift/chapter_heap/heap.swift b/ru/codes/swift/chapter_heap/heap.swift index dc24f2e6c..93826b12f 100644 --- a/ru/codes/swift/chapter_heap/heap.swift +++ b/ru/codes/swift/chapter_heap/heap.swift @@ -4,58 +4,76 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{import} import HeapModule +// [endregion]{import} import utils -func testPush(heap: inout Heap, val: Int) { - heap.insert(val) - print("\nПосле добавления элемента \(val) в кучу\n") - PrintUtil.printHeap(queue: heap.unordered) -} - -func testPop(heap: inout Heap) { - let val = heap.removeMax() - print("\nПосле извлечения элемента вершины кучи \(val)\n") - PrintUtil.printHeap(queue: heap.unordered) -} - @main enum _Heap { /* Driver Code */ static func main() { + // [region]{init} /* Инициализация кучи */ // Тип Heap в Swift одновременно поддерживает максимальную и минимальную кучу var heap = Heap() + // [endregion]{init} + // [region]{push} /* Добавление элемента в кучу */ - testPush(heap: &heap, val: 1) - testPush(heap: &heap, val: 3) - testPush(heap: &heap, val: 2) - testPush(heap: &heap, val: 5) - testPush(heap: &heap, val: 4) + heap.insert(1) + heap.insert(3) + heap.insert(2) + heap.insert(5) + heap.insert(4) + // [endregion]{push} + PrintUtil.printHeap(queue: heap.unordered) + // [region]{peek} /* Получение элемента с вершины кучи */ - let peek = heap.max() + var peek = heap.max() + // [endregion]{peek} print("\nЭлемент на вершине кучи = \(peek!)\n") + // [region]{pop_1} /* Извлечение элемента с вершины кучи */ - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) + peek = heap.removeMax() // 5 + // [endregion]{pop_1} + print(peek!) + // [region]{pop_2} + peek = heap.removeMax() // 4 + // [endregion]{pop_2} + print(peek!) + // [region]{pop_3} + peek = heap.removeMax() // 3 + // [endregion]{pop_3} + print(peek!) + // [region]{pop_4} + peek = heap.removeMax() // 2 + // [endregion]{pop_4} + print(peek!) + // [region]{pop_5} + peek = heap.removeMax() // 1 + // [endregion]{pop_5} + print(peek!) + // [region]{size} /* Получение размера кучи */ let size = heap.count + // [endregion]{size} print("\nКоличество элементов в куче = \(size)\n") + // [region]{is_empty} /* Проверка, пуста ли куча */ let isEmpty = heap.isEmpty + // [endregion]{is_empty} print("\nПуста ли куча: \(isEmpty)\n") + // [region]{heapify} /* Построить кучу по входному списку */ // Временная сложность равна O(n), а не O(nlogn) let heap2 = Heap([1, 3, 2, 5, 4]) + // [endregion]{heapify} print("\nПосле построения кучи из входного списка") PrintUtil.printHeap(queue: heap2.unordered) } diff --git a/ru/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift b/ru/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift index 04450fd40..7c70158c5 100644 --- a/ru/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift +++ b/ru/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift @@ -4,6 +4,7 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{doubly_list_node} /* Узел двусвязного списка */ class ListNode { var val: Int // Значение узла @@ -14,6 +15,7 @@ class ListNode { self.val = val } } +// [endregion]{doubly_list_node} /* Двусторонняя очередь на основе двусвязного списка */ class LinkedListDeque { 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..45ec8c6c6 100644 --- a/ru/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts +++ b/ru/codes/typescript/chapter_stack_and_queue/linkedlist_deque.ts @@ -4,10 +4,11 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* Узел двусвязного списка */ class ListNode { - prev: ListNode; // Ссылка на узел-предшественник (указатель) - next: ListNode; // Ссылка на узел-преемник (указатель) + prev: ListNode | null; // Ссылка на узел-предшественник (указатель) + next: ListNode | null; // Ссылка на узел-преемник (указатель) val: number; // Значение узла constructor(val: number) { @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* Двусторонняя очередь на основе двусвязного списка */ class LinkedListDeque { diff --git a/ru/codes/typescript/modules/ListNode.ts b/ru/codes/typescript/modules/ListNode.ts index ba514b534..54f00dc5f 100644 --- a/ru/codes/typescript/modules/ListNode.ts +++ b/ru/codes/typescript/modules/ListNode.ts @@ -4,15 +4,17 @@ * Author: Justin (xiefahit@gmail.com) */ +// [region]{list_node} /* Узел связного списка */ 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; } } +// [endregion]{list_node} /* Десериализовать массив в связный список */ function arrToLinkedList(arr: number[]): ListNode | null { 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..dcd26e66d 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 @@ -6,6 +6,7 @@ #include "../utils/common.h" +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ typedef struct DoublyListNode { int val; // 節點值 @@ -21,6 +22,7 @@ DoublyListNode *newDoublyListNode(int num) { new->prev = NULL; return new; } +// [endregion]{doubly_list_node} /* 析構函式 */ void delDoublyListNode(DoublyListNode *node) { diff --git a/zh-hant/codes/c/utils/list_node.h b/zh-hant/codes/c/utils/list_node.h index 73567a1bc..0a8d18598 100644 --- a/zh-hant/codes/c/utils/list_node.h +++ b/zh-hant/codes/c/utils/list_node.h @@ -11,6 +11,7 @@ extern "C" { #endif +// [region]{list_node} /* 鏈結串列節點結構體 */ typedef struct ListNode { int val; // 節點值 @@ -25,6 +26,7 @@ ListNode *newListNode(int val) { node->next = NULL; return node; } +// [endregion]{list_node} /* 將陣列反序列化為鏈結串列 */ ListNode *arrToLinkedList(const int *arr, size_t size) { diff --git a/zh-hant/codes/cpp/chapter_heap/heap.cpp b/zh-hant/codes/cpp/chapter_heap/heap.cpp index c02463ffe..9eea5f9d0 100644 --- a/zh-hant/codes/cpp/chapter_heap/heap.cpp +++ b/zh-hant/codes/cpp/chapter_heap/heap.cpp @@ -6,59 +6,75 @@ #include "../utils/common.hpp" -void testPush(priority_queue &heap, int val) { - heap.push(val); // 元素入堆積 - cout << "\n元素 " << val << " 入堆積後" << endl; - printHeap(heap); -} - -void testPop(priority_queue &heap) { - int val = heap.top(); - heap.pop(); - cout << "\n堆積頂元素 " << val << " 出堆積後" << endl; - printHeap(heap); -} - /* Driver Code */ int main() { + // [region]{init} /* 初始化堆積 */ // 初始化小頂堆積 - // priority_queue, greater> minHeap; + priority_queue, greater> minHeap; // 初始化大頂堆積 priority_queue, less> maxHeap; + // [endregion]{init} cout << "\n以下測試樣例為大頂堆積" << endl; + // [region]{push} /* 元素入堆積 */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.push(1); + maxHeap.push(3); + maxHeap.push(2); + maxHeap.push(5); + maxHeap.push(4); + // [endregion]{push} + printHeap(maxHeap); + // [region]{peek} /* 獲取堆積頂元素 */ - int peek = maxHeap.top(); + int peek = maxHeap.top(); // 5 + // [endregion]{peek} cout << "\n堆積頂元素為 " << peek << endl; + // [region]{pop_1} /* 堆積頂元素出堆積 */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // 出堆積元素會形成一個從大到小的序列 + maxHeap.pop(); // 5 + // [endregion]{pop_1} + printHeap(maxHeap); + // [region]{pop_2} + maxHeap.pop(); // 4 + // [endregion]{pop_2} + printHeap(maxHeap); + // [region]{pop_3} + maxHeap.pop(); // 3 + // [endregion]{pop_3} + printHeap(maxHeap); + // [region]{pop_4} + maxHeap.pop(); // 2 + // [endregion]{pop_4} + printHeap(maxHeap); + // [region]{pop_5} + maxHeap.pop(); // 1 + // [endregion]{pop_5} + printHeap(maxHeap); + // [region]{size} /* 獲取堆積大小 */ int size = maxHeap.size(); + // [endregion]{size} cout << "\n堆積元素數量為 " << size << endl; + // [region]{is_empty} /* 判斷堆積是否為空 */ bool isEmpty = maxHeap.empty(); + // [endregion]{is_empty} cout << "\n堆積是否為空 " << isEmpty << endl; + // [region]{heapify} /* 輸入串列並建堆積 */ // 時間複雜度為 O(n) ,而非 O(nlogn) vector input{1, 3, 2, 5, 4}; - priority_queue, greater> minHeap(input.begin(), input.end()); + minHeap = priority_queue, greater>(input.begin(), input.end()); + // [endregion]{heapify} cout << "輸入串列並建立小頂堆積後" << endl; printHeap(minHeap); diff --git a/zh-hant/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp b/zh-hant/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp index 944cce0f4..cf4e56e28 100644 --- a/zh-hant/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp +++ b/zh-hant/codes/cpp/chapter_stack_and_queue/linkedlist_deque.cpp @@ -6,6 +6,7 @@ #include "../utils/common.hpp" +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ struct DoublyListNode { int val; // 節點值 @@ -14,6 +15,7 @@ struct DoublyListNode { DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) { } }; +// [endregion]{doubly_list_node} /* 基於雙向鏈結串列實現的雙向佇列 */ class LinkedListDeque { diff --git a/zh-hant/codes/cpp/utils/list_node.hpp b/zh-hant/codes/cpp/utils/list_node.hpp index e3b7e2389..bab1f0c51 100644 --- a/zh-hant/codes/cpp/utils/list_node.hpp +++ b/zh-hant/codes/cpp/utils/list_node.hpp @@ -11,13 +11,15 @@ using namespace std; +// [region]{list_node} /* 鏈結串列節點 */ struct ListNode { - int val; - ListNode *next; + int val; // 節點值 + ListNode *next; // 後繼節點指標 ListNode(int x) : val(x), next(nullptr) { } }; +// [endregion]{list_node} /* 將串列反序列化為鏈結串列 */ ListNode *vecToLinkedList(vector list) { diff --git a/zh-hant/codes/csharp/chapter_heap/heap.cs b/zh-hant/codes/csharp/chapter_heap/heap.cs index 71289029e..af4a3a24e 100644 --- a/zh-hant/codes/csharp/chapter_heap/heap.cs +++ b/zh-hant/codes/csharp/chapter_heap/heap.cs @@ -7,57 +7,72 @@ namespace hello_algo.chapter_heap; public class heap { - void TestPush(PriorityQueue heap, int val) { - heap.Enqueue(val, val); // 元素入堆積 - Console.WriteLine($"\n元素 {val} 入堆積後\n"); - PrintUtil.PrintHeap(heap); - } - - void TestPop(PriorityQueue heap) { - int val = heap.Dequeue(); // 堆積頂元素出堆積 - Console.WriteLine($"\n堆積頂元素 {val} 出堆積後\n"); - PrintUtil.PrintHeap(heap); - } - [Test] public void Test() { + // [region]{init} /* 初始化堆積 */ // 初始化小頂堆積 PriorityQueue minHeap = new(); // 初始化大頂堆積(使用 lambda 表示式修改 Comparer 即可) PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); + // [endregion]{init} Console.WriteLine("以下測試樣例為大頂堆積"); + // [region]{push} /* 元素入堆積 */ - TestPush(maxHeap, 1); - TestPush(maxHeap, 3); - TestPush(maxHeap, 2); - TestPush(maxHeap, 5); - TestPush(maxHeap, 4); + maxHeap.Enqueue(1, 1); + maxHeap.Enqueue(3, 3); + maxHeap.Enqueue(2, 2); + maxHeap.Enqueue(5, 5); + maxHeap.Enqueue(4, 4); + // [endregion]{push} + PrintUtil.PrintHeap(maxHeap); + // [region]{peek} /* 獲取堆積頂元素 */ - int peek = maxHeap.Peek(); + int peek = maxHeap.Peek(); // 5 + // [endregion]{peek} Console.WriteLine($"堆積頂元素為 {peek}"); + // [region]{pop_1} /* 堆積頂元素出堆積 */ // 出堆積元素會形成一個從大到小的序列 - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); - TestPop(maxHeap); + peek = maxHeap.Dequeue(); // 5 + // [endregion]{pop_1} + Console.WriteLine(peek); + // [region]{pop_2} + peek = maxHeap.Dequeue(); // 4 + // [endregion]{pop_2} + Console.WriteLine(peek); + // [region]{pop_3} + peek = maxHeap.Dequeue(); // 3 + // [endregion]{pop_3} + Console.WriteLine(peek); + // [region]{pop_4} + peek = maxHeap.Dequeue(); // 2 + // [endregion]{pop_4} + Console.WriteLine(peek); + // [region]{pop_5} + peek = maxHeap.Dequeue(); // 1 + // [endregion]{pop_5} + Console.WriteLine(peek); + // [region]{size} /* 獲取堆積大小 */ int size = maxHeap.Count; + // [endregion]{size} Console.WriteLine($"堆積元素數量為 {size}"); + // [region]{is_empty} /* 判斷堆積是否為空 */ bool isEmpty = maxHeap.Count == 0; + // [endregion]{is_empty} Console.WriteLine($"堆積是否為空 {isEmpty}"); + // [region]{heapify} /* 輸入串列並建堆積 */ - var list = new int[] { 1, 3, 2, 5, 4 }; - minHeap = new PriorityQueue(list.Select(x => (x, x))); + minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); + // [endregion]{heapify} Console.WriteLine("輸入串列並建立小頂堆積後"); PrintUtil.PrintHeap(minHeap); } diff --git a/zh-hant/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs b/zh-hant/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs index a0c2a1a28..ac860138d 100644 --- a/zh-hant/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs +++ b/zh-hant/codes/csharp/chapter_stack_and_queue/linkedlist_deque.cs @@ -6,12 +6,14 @@ namespace hello_algo.chapter_stack_and_queue; +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ public class ListNode(int val) { - public int val = val; // 節點值 + public int val = val; // 節點值 public ListNode? next = null; // 後繼節點引用 public ListNode? prev = null; // 前驅節點引用 } +// [endregion]{doubly_list_node} /* 基於雙向鏈結串列實現的雙向佇列 */ public class LinkedListDeque { diff --git a/zh-hant/codes/csharp/utils/ListNode.cs b/zh-hant/codes/csharp/utils/ListNode.cs index 30047c487..da06fe8d3 100644 --- a/zh-hant/codes/csharp/utils/ListNode.cs +++ b/zh-hant/codes/csharp/utils/ListNode.cs @@ -4,10 +4,12 @@ namespace hello_algo.utils; +// [region]{list_node} /* 鏈結串列節點 */ public class ListNode(int x) { - public int val = x; - public ListNode? next; + public int val = x; // 節點值 + public ListNode? next; // 指向下一節點的引用 +// [endregion]{list_node} /* 將陣列反序列化為鏈結串列 */ public static ListNode? ArrToLinkedList(int[] arr) { @@ -29,4 +31,6 @@ public class ListNode(int x) { } return string.Join("->", list); } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/zh-hant/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart b/zh-hant/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart index 0ef491737..cf8a5b6ce 100644 --- a/zh-hant/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart +++ b/zh-hant/codes/dart/chapter_stack_and_queue/linkedlist_deque.dart @@ -4,6 +4,7 @@ * Author: liuyuxin (gvenusleo@gmail.com) */ +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ class ListNode { int val; // 節點值 @@ -12,6 +13,7 @@ class ListNode { ListNode(this.val, {this.next, this.prev}); } +// [endregion]{doubly_list_node} /* 基於雙向鏈結串列實現的雙向對列 */ class LinkedListDeque { diff --git a/zh-hant/codes/dart/utils/list_node.dart b/zh-hant/codes/dart/utils/list_node.dart index b240a0c16..0be2bfd41 100644 --- a/zh-hant/codes/dart/utils/list_node.dart +++ b/zh-hant/codes/dart/utils/list_node.dart @@ -4,13 +4,15 @@ * Author: Jefferson (JeffersonHuang77@gmail.com) */ +// [region]{list_node} /* 鏈結串列節點 */ class ListNode { - int val; - ListNode? next; + int val; // 節點值 + ListNode? next; // 指向下一節點的引用 - ListNode(this.val, [this.next]); + ListNode(this.val, [this.next]); // 建構子 } +// [endregion]{list_node} /* 將串列反序列化為鏈結串列 */ ListNode? listToLinkedList(List list) { diff --git a/zh-hant/codes/go/chapter_heap/heap.go b/zh-hant/codes/go/chapter_heap/heap.go index 765556a49..f0467d734 100644 --- a/zh-hant/codes/go/chapter_heap/heap.go +++ b/zh-hant/codes/go/chapter_heap/heap.go @@ -4,6 +4,7 @@ package chapter_heap +// [region]{int_heap} // Go 語言中可以透過實現 heap.Interface 來構建整數大頂堆積 // 實現 heap.Interface 需要同時實現 sort.Interface type intHeap []any @@ -43,3 +44,5 @@ func (h *intHeap) Swap(i, j int) { func (h *intHeap) Top() any { return (*h)[0] } + +// [endregion]{int_heap} diff --git a/zh-hant/codes/go/chapter_heap/heap_test.go b/zh-hant/codes/go/chapter_heap/heap_test.go index 3fb6e1ae4..5f16aa6c8 100644 --- a/zh-hant/codes/go/chapter_heap/heap_test.go +++ b/zh-hant/codes/go/chapter_heap/heap_test.go @@ -13,42 +13,32 @@ import ( . "github.com/krahets/hello-algo/pkg" ) -func testPush(h *intHeap, val int) { - // 呼叫 heap.Interface 的函式,來新增元素 - heap.Push(h, val) - fmt.Printf("\n元素 %d 入堆積後 \n", val) - PrintHeap(*h) -} - -func testPop(h *intHeap) { - // 呼叫 heap.Interface 的函式,來移除元素 - val := heap.Pop(h) - fmt.Printf("\n堆積頂元素 %d 出堆積後 \n", val) - PrintHeap(*h) -} - +// [region]{test_heap} func TestHeap(t *testing.T) { /* 初始化堆積 */ // 初始化大頂堆積 maxHeap := &intHeap{} heap.Init(maxHeap) /* 元素入堆積 */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + // 呼叫 heap.Interface 的函式,來新增元素 + heap.Push(maxHeap, 1) + heap.Push(maxHeap, 3) + heap.Push(maxHeap, 2) + heap.Push(maxHeap, 5) + heap.Push(maxHeap, 4) + PrintHeap(*maxHeap) /* 獲取堆積頂元素 */ top := maxHeap.Top() fmt.Printf("堆積頂元素為 %d\n", top) /* 堆積頂元素出堆積 */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // 呼叫 heap.Interface 的函式,來移除元素 + fmt.Println(heap.Pop(maxHeap)) // 5 + fmt.Println(heap.Pop(maxHeap)) // 4 + fmt.Println(heap.Pop(maxHeap)) // 3 + fmt.Println(heap.Pop(maxHeap)) // 2 + fmt.Println(heap.Pop(maxHeap)) // 1 /* 獲取堆積大小 */ size := len(*maxHeap) @@ -59,6 +49,8 @@ func TestHeap(t *testing.T) { fmt.Printf("堆積是否為空 %t\n", isEmpty) } +// [endregion]{test_heap} + func TestMyHeap(t *testing.T) { /* 初始化堆積 */ // 初始化大頂堆積 diff --git a/zh-hant/codes/go/pkg/list_node.go b/zh-hant/codes/go/pkg/list_node.go index c88bbf493..69aa6f75c 100644 --- a/zh-hant/codes/go/pkg/list_node.go +++ b/zh-hant/codes/go/pkg/list_node.go @@ -4,20 +4,23 @@ package pkg +// [region]{list_node} // ListNode 鏈結串列節點 type ListNode struct { - Next *ListNode - Val int + Val int // 節點值 + Next *ListNode // 後繼節點指標 } // NewListNode 鏈結串列節點建構子 func NewListNode(v int) *ListNode { return &ListNode{ - Next: nil, Val: v, + Next: nil, } } +// [endregion]{list_node} + // ArrayToLinkedList 將陣列反序列化為鏈結串列 func ArrayToLinkedList(arr []int) *ListNode { // dummy header of linked list diff --git a/zh-hant/codes/java/chapter_heap/heap.java b/zh-hant/codes/java/chapter_heap/heap.java index 407c82678..6a3e36b3c 100644 --- a/zh-hant/codes/java/chapter_heap/heap.java +++ b/zh-hant/codes/java/chapter_heap/heap.java @@ -10,56 +10,73 @@ import utils.*; import java.util.*; public class heap { - public static void testPush(Queue heap, int val) { - heap.offer(val); // 元素入堆積 - System.out.format("\n元素 %d 入堆積後\n", val); - PrintUtil.printHeap(heap); - } - - public static void testPop(Queue heap) { - int val = heap.poll(); // 堆積頂元素出堆積 - System.out.format("\n堆積頂元素 %d 出堆積後\n", val); - PrintUtil.printHeap(heap); - } - public static void main(String[] args) { + // [region]{init} /* 初始化堆積 */ // 初始化小頂堆積 Queue minHeap = new PriorityQueue<>(); // 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可) Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); + // [endregion]{init} System.out.println("\n以下測試樣例為大頂堆積"); + // [region]{push} /* 元素入堆積 */ - testPush(maxHeap, 1); - testPush(maxHeap, 3); - testPush(maxHeap, 2); - testPush(maxHeap, 5); - testPush(maxHeap, 4); + maxHeap.offer(1); + maxHeap.offer(3); + maxHeap.offer(2); + maxHeap.offer(5); + maxHeap.offer(4); + // [endregion]{push} + PrintUtil.printHeap(maxHeap); + // [region]{peek} /* 獲取堆積頂元素 */ - int peek = maxHeap.peek(); + int peek = maxHeap.peek(); // 5 + // [endregion]{peek} System.out.format("\n堆積頂元素為 %d\n", peek); + // [region]{pop_1} /* 堆積頂元素出堆積 */ - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); - testPop(maxHeap); + // 出堆積元素會形成一個從大到小的序列 + peek = maxHeap.poll(); // 5 + // [endregion]{pop_1} + System.out.println(peek); + // [region]{pop_2} + peek = maxHeap.poll(); // 4 + // [endregion]{pop_2} + System.out.println(peek); + // [region]{pop_3} + peek = maxHeap.poll(); // 3 + // [endregion]{pop_3} + System.out.println(peek); + // [region]{pop_4} + peek = maxHeap.poll(); // 2 + // [endregion]{pop_4} + System.out.println(peek); + // [region]{pop_5} + peek = maxHeap.poll(); // 1 + // [endregion]{pop_5} + System.out.println(peek); + // [region]{size} /* 獲取堆積大小 */ int size = maxHeap.size(); + // [endregion]{size} System.out.format("\n堆積元素數量為 %d\n", size); + // [region]{is_empty} /* 判斷堆積是否為空 */ boolean isEmpty = maxHeap.isEmpty(); + // [endregion]{is_empty} System.out.format("\n堆積是否為空 %b\n", isEmpty); + // [region]{heapify} /* 輸入串列並建堆積 */ // 時間複雜度為 O(n) ,而非 O(nlogn) minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); + // [endregion]{heapify} System.out.println("\n輸入串列並建立小頂堆積後"); PrintUtil.printHeap(minHeap); } diff --git a/zh-hant/codes/java/chapter_stack_and_queue/linkedlist_deque.java b/zh-hant/codes/java/chapter_stack_and_queue/linkedlist_deque.java index 6889a8c26..e5f76d7ce 100644 --- a/zh-hant/codes/java/chapter_stack_and_queue/linkedlist_deque.java +++ b/zh-hant/codes/java/chapter_stack_and_queue/linkedlist_deque.java @@ -8,9 +8,10 @@ package chapter_stack_and_queue; import java.util.*; +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ class ListNode { - int val; // 節點值 + int val; // 節點值 ListNode next; // 後繼節點引用 ListNode prev; // 前驅節點引用 @@ -19,6 +20,7 @@ class ListNode { prev = next = null; } } +// [endregion]{doubly_list_node} /* 基於雙向鏈結串列實現的雙向佇列 */ class LinkedListDeque { diff --git a/zh-hant/codes/java/utils/ListNode.java b/zh-hant/codes/java/utils/ListNode.java index e1ce13631..cad5aa6f9 100755 --- a/zh-hant/codes/java/utils/ListNode.java +++ b/zh-hant/codes/java/utils/ListNode.java @@ -6,14 +6,16 @@ package utils; +// [region]{list_node} /* 鏈結串列節點 */ public class ListNode { - public int val; - public ListNode next; + public int val; // 節點值 + public ListNode next; // 指向下一節點的引用 public ListNode(int x) { val = x; } +// [endregion]{list_node} /* 將串列反序列化為鏈結串列 */ public static ListNode arrToLinkedList(int[] arr) { @@ -25,4 +27,6 @@ public class ListNode { } return dum.next; } +// [region]{list_node_end} } +// [endregion]{list_node_end} diff --git a/zh-hant/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js b/zh-hant/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js index c66a161da..3361c2428 100644 --- a/zh-hant/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js +++ b/zh-hant/codes/javascript/chapter_stack_and_queue/linkedlist_deque.js @@ -4,6 +4,7 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ class ListNode { prev; // 前驅節點引用 (指標) @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* 基於雙向鏈結串列實現的雙向佇列 */ class LinkedListDeque { diff --git a/zh-hant/codes/javascript/modules/ListNode.js b/zh-hant/codes/javascript/modules/ListNode.js index e6f8b3d88..05a39091b 100755 --- a/zh-hant/codes/javascript/modules/ListNode.js +++ b/zh-hant/codes/javascript/modules/ListNode.js @@ -4,6 +4,7 @@ * Author: IsChristina (christinaxia77@foxmail.com) */ +// [region]{list_node} /* 鏈結串列節點 */ class ListNode { val; // 節點值 @@ -13,6 +14,7 @@ class ListNode { this.next = next === undefined ? null : next; } } +// [endregion]{list_node} /* 將串列反序列化為鏈結串列 */ function arrToLinkedList(arr) { diff --git a/zh-hant/codes/kotlin/chapter_heap/heap.kt b/zh-hant/codes/kotlin/chapter_heap/heap.kt index 5a4320032..243811291 100644 --- a/zh-hant/codes/kotlin/chapter_heap/heap.kt +++ b/zh-hant/codes/kotlin/chapter_heap/heap.kt @@ -9,58 +9,74 @@ package chapter_heap import utils.printHeap import java.util.* -fun testPush(heap: Queue, _val: Int) { - heap.offer(_val) // 元素入堆積 - print("\n元素 $_val 入堆積後\n") - printHeap(heap) -} - -fun testPop(heap: Queue) { - val _val = heap.poll() // 堆積頂元素出堆積 - print("\n堆積頂元素 $_val 出堆積後\n") - printHeap(heap) -} - /* Driver Code */ fun main() { + // [region]{init} /* 初始化堆積 */ // 初始化小頂堆積 var minHeap = PriorityQueue() - // 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可) val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } + // [endregion]{init} println("\n以下測試樣例為大頂堆積") + // [region]{push} /* 元素入堆積 */ - testPush(maxHeap, 1) - testPush(maxHeap, 3) - testPush(maxHeap, 2) - testPush(maxHeap, 5) - testPush(maxHeap, 4) + maxHeap.offer(1) + maxHeap.offer(3) + maxHeap.offer(2) + maxHeap.offer(5) + maxHeap.offer(4) + // [endregion]{push} + printHeap(maxHeap) + // [region]{peek} /* 獲取堆積頂元素 */ - val peek = maxHeap.peek() + var peek = maxHeap.peek() // 5 + // [endregion]{peek} print("\n堆積頂元素為 $peek\n") + // [region]{pop_1} /* 堆積頂元素出堆積 */ - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) - testPop(maxHeap) + // 出堆積元素會形成一個從大到小的序列 + peek = maxHeap.poll() // 5 + // [endregion]{pop_1} + println(peek) + // [region]{pop_2} + peek = maxHeap.poll() // 4 + // [endregion]{pop_2} + println(peek) + // [region]{pop_3} + peek = maxHeap.poll() // 3 + // [endregion]{pop_3} + println(peek) + // [region]{pop_4} + peek = maxHeap.poll() // 2 + // [endregion]{pop_4} + println(peek) + // [region]{pop_5} + peek = maxHeap.poll() // 1 + // [endregion]{pop_5} + println(peek) + // [region]{size} /* 獲取堆積大小 */ val size = maxHeap.size + // [endregion]{size} print("\n堆積元素數量為 $size\n") + // [region]{is_empty} /* 判斷堆積是否為空 */ val isEmpty = maxHeap.isEmpty() + // [endregion]{is_empty} print("\n堆積是否為空 $isEmpty\n") + // [region]{heapify} /* 輸入串列並建堆積 */ // 時間複雜度為 O(n) ,而非 O(nlogn) minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) + // [endregion]{heapify} println("\n輸入串列並建立小頂堆積後") printHeap(minHeap) } \ No newline at end of file diff --git a/zh-hant/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt b/zh-hant/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt index 54a440a26..d7f54f9cb 100644 --- a/zh-hant/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt +++ b/zh-hant/codes/kotlin/chapter_stack_and_queue/linkedlist_deque.kt @@ -6,12 +6,14 @@ package chapter_stack_and_queue +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ class ListNode(var _val: Int) { // 節點值 var next: ListNode? = null // 後繼節點引用 var prev: ListNode? = null // 前驅節點引用 } +// [endregion]{doubly_list_node} /* 基於雙向鏈結串列實現的雙向佇列 */ class LinkedListDeque { @@ -162,4 +164,4 @@ fun main() { /* 判斷雙向佇列是否為空 */ val isEmpty = deque.isEmpty() println("雙向佇列是否為空 = $isEmpty") -} \ No newline at end of file +} diff --git a/zh-hant/codes/kotlin/utils/ListNode.kt b/zh-hant/codes/kotlin/utils/ListNode.kt index 0bd701596..4a9437427 100644 --- a/zh-hant/codes/kotlin/utils/ListNode.kt +++ b/zh-hant/codes/kotlin/utils/ListNode.kt @@ -6,9 +6,11 @@ package utils +// [region]{list_node} /* 鏈結串列節點 */ class ListNode(var _val: Int) { - var next: ListNode? = null + var next: ListNode? = null // 指向下一節點的引用 +// [endregion]{list_node} companion object { /* 將串列反序列化為鏈結串列 */ @@ -22,4 +24,6 @@ class ListNode(var _val: Int) { return dum.next } } -} \ No newline at end of file +// [region]{list_node_end} +} +// [endregion]{list_node_end} diff --git a/zh-hant/codes/python/chapter_heap/heap.py b/zh-hant/codes/python/chapter_heap/heap.py index 8c077a773..063439020 100644 --- a/zh-hant/codes/python/chapter_heap/heap.py +++ b/zh-hant/codes/python/chapter_heap/heap.py @@ -13,59 +13,76 @@ from modules import print_heap import heapq -def test_push(heap: list, val: int, flag: int = 1): - heapq.heappush(heap, flag * val) # 元素入堆積 - print(f"\n元素 {val} 入堆積後") - print_heap([flag * val for val in heap]) - - -def test_pop(heap: list, flag: int = 1): - val = flag * heapq.heappop(heap) # 堆積頂元素出堆積 - print(f"\n堆積頂元素 {val} 出堆積後") - print_heap([flag * val for val in heap]) - - """Driver Code""" if __name__ == "__main__": + # [region]{init} # 初始化小頂堆積 min_heap, flag = [], 1 # 初始化大頂堆積 max_heap, flag = [], -1 - print("\n以下測試樣例為大頂堆積") # Python 的 heapq 模組預設實現小頂堆積 # 考慮將“元素取負”後再入堆積,這樣就可以將大小關係顛倒,從而實現大頂堆積 # 在本示例中,flag = 1 時對應小頂堆積,flag = -1 時對應大頂堆積 + # [endregion]{init} + print("\n以下測試樣例為大頂堆積") + # [region]{push} # 元素入堆積 - test_push(max_heap, 1, flag) - test_push(max_heap, 3, flag) - test_push(max_heap, 2, flag) - test_push(max_heap, 5, flag) - test_push(max_heap, 4, flag) + 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) + # [endregion]{push} + print_heap([flag * val for val in max_heap]) + # [region]{peek} # 獲取堆積頂元素 - peek: int = flag * max_heap[0] + peek: int = flag * max_heap[0] # 5 + # [endregion]{peek} print(f"\n堆積頂元素為 {peek}") + # [region]{pop_1} # 堆積頂元素出堆積 - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) - test_pop(max_heap, flag) + # 出堆積元素會形成一個從大到小的序列 + val = flag * heapq.heappop(max_heap) # 5 + # [endregion]{pop_1} + print(val) + # [region]{pop_2} + val = flag * heapq.heappop(max_heap) # 4 + # [endregion]{pop_2} + print(val) + # [region]{pop_3} + val = flag * heapq.heappop(max_heap) # 3 + # [endregion]{pop_3} + print(val) + # [region]{pop_4} + val = flag * heapq.heappop(max_heap) # 2 + # [endregion]{pop_4} + print(val) + # [region]{pop_5} + val = flag * heapq.heappop(max_heap) # 1 + # [endregion]{pop_5} + print(val) + # [region]{size} # 獲取堆積大小 size: int = len(max_heap) + # [endregion]{size} print(f"\n堆積元素數量為 {size}") + # [region]{is_empty} # 判斷堆積是否為空 is_empty: bool = not max_heap + # [endregion]{is_empty} print(f"\n堆積是否為空 {is_empty}") + # [region]{heapify} # 輸入串列並建堆積 # 時間複雜度為 O(n) ,而非 O(nlogn) - min_heap = [1, 3, 2, 5, 4] + min_heap: list[int] = [1, 3, 2, 5, 4] heapq.heapify(min_heap) + # [endregion]{heapify} print("\n輸入串列並建立小頂堆積後") print_heap(min_heap) diff --git a/zh-hant/codes/python/chapter_stack_and_queue/linkedlist_deque.py b/zh-hant/codes/python/chapter_stack_and_queue/linkedlist_deque.py index 68674e6a6..ea4ba0021 100644 --- a/zh-hant/codes/python/chapter_stack_and_queue/linkedlist_deque.py +++ b/zh-hant/codes/python/chapter_stack_and_queue/linkedlist_deque.py @@ -5,14 +5,16 @@ Author: krahets (krahets@163.com) """ +# [region]{doubly_list_node} 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 # 前驅節點引用 +# [endregion]{doubly_list_node} class LinkedListDeque: diff --git a/zh-hant/codes/python/modules/list_node.py b/zh-hant/codes/python/modules/list_node.py index 40a5fa458..2321f41c5 100644 --- a/zh-hant/codes/python/modules/list_node.py +++ b/zh-hant/codes/python/modules/list_node.py @@ -5,12 +5,14 @@ Author: krahets (krahets@163.com) """ +# [region]{list_node} class ListNode: """鏈結串列節點類別""" def __init__(self, val: int): self.val: int = val # 節點值 - self.next: ListNode | None = None # 後繼節點引用 + self.next: ListNode | None = None # 指向下一節點的引用 +# [endregion]{list_node} def list_to_linked_list(arr: list[int]) -> ListNode | None: 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..07362f67a 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,17 +4,19 @@ Created Time: 2024-04-06 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{doubly_list_node} ### 雙向鏈結串列節點 class ListNode - attr_accessor :val + attr_accessor :val # 節點值 attr_accessor :next # 後繼節點引用 - attr_accessor :prev # 前軀節點引用 + attr_accessor :prev # 前驅節點引用 ### 建構子 ### def initialize(val) @val = val end end +# [endregion]{doubly_list_node} ### 基於雙向鏈結串列實現的雙向佇列 ### class LinkedListDeque diff --git a/zh-hant/codes/ruby/utils/list_node.rb b/zh-hant/codes/ruby/utils/list_node.rb index b09d382e8..349effcd3 100644 --- a/zh-hant/codes/ruby/utils/list_node.rb +++ b/zh-hant/codes/ruby/utils/list_node.rb @@ -4,6 +4,7 @@ Created Time: 2024-03-18 Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com) =end +# [region]{list_node} ### 鏈結串列節點類別 ### class ListNode attr_accessor :val # 節點值 @@ -14,6 +15,7 @@ class ListNode @next = next_node end end +# [endregion]{list_node} ### 將串列反序列化為鏈結串列 ### def arr_to_linked_list(arr) diff --git a/zh-hant/codes/rust/chapter_heap/heap.rs b/zh-hant/codes/rust/chapter_heap/heap.rs index 847db90fc..437f8c79a 100644 --- a/zh-hant/codes/rust/chapter_heap/heap.rs +++ b/zh-hant/codes/rust/chapter_heap/heap.rs @@ -6,22 +6,13 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::{cmp::Reverse, collections::BinaryHeap}; - -fn test_push_max(heap: &mut BinaryHeap, val: i32) { - heap.push(val); // 元素入堆積 - println!("\n元素 {} 入堆積後", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} - -fn test_pop_max(heap: &mut BinaryHeap) { - let val = heap.pop().unwrap(); - println!("\n堆積頂元素 {} 出堆積後", val); - print_util::print_heap(heap.iter().map(|&val| val).collect()); -} +// [endregion]{import} /* Driver Code */ fn main() { + // [region]{init} /* 初始化堆積 */ // 初始化小頂堆積 #[allow(unused_assignments)] @@ -29,43 +20,66 @@ fn main() { // Rust 的 BinaryHeap 是大頂堆積,小頂堆積一般會“套上”Reverse // 初始化大頂堆積 let mut max_heap = BinaryHeap::new(); + // [endregion]{init} println!("\n以下測試樣例為大頂堆積"); + // [region]{push} /* 元素入堆積 */ - test_push_max(&mut max_heap, 1); - test_push_max(&mut max_heap, 3); - test_push_max(&mut max_heap, 2); - test_push_max(&mut max_heap, 5); - test_push_max(&mut max_heap, 4); + max_heap.push(1); + max_heap.push(3); + max_heap.push(2); + max_heap.push(5); + max_heap.push(4); + // [endregion]{push} + print_util::print_heap(max_heap.iter().map(|&val| val).collect()); + // [region]{peek} /* 獲取堆積頂元素 */ - let peek = max_heap.peek().unwrap(); + let peek = max_heap.peek().unwrap(); // 5 + // [endregion]{peek} println!("\n堆積頂元素為 {}", peek); + // [region]{pop_1} /* 堆積頂元素出堆積 */ - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); - test_pop_max(&mut max_heap); + // 出堆積元素會形成一個從大到小的序列 + let peek = max_heap.pop().unwrap(); // 5 + // [endregion]{pop_1} + println!("{}", peek); + // [region]{pop_2} + let peek = max_heap.pop().unwrap(); // 4 + // [endregion]{pop_2} + println!("{}", peek); + // [region]{pop_3} + let peek = max_heap.pop().unwrap(); // 3 + // [endregion]{pop_3} + println!("{}", peek); + // [region]{pop_4} + let peek = max_heap.pop().unwrap(); // 2 + // [endregion]{pop_4} + println!("{}", peek); + // [region]{pop_5} + let peek = max_heap.pop().unwrap(); // 1 + // [endregion]{pop_5} + println!("{}", peek); + // [region]{size} /* 獲取堆積大小 */ let size = max_heap.len(); + // [endregion]{size} println!("\n堆積元素數量為 {}", size); + // [region]{is_empty} /* 判斷堆積是否為空 */ let is_empty = max_heap.is_empty(); + // [endregion]{is_empty} println!("\n堆積是否為空 {}", is_empty); + // [region]{heapify} /* 輸入串列並建堆積 */ // 時間複雜度為 O(n) ,而非 O(nlogn) - min_heap = BinaryHeap::from( - vec![1, 3, 2, 5, 4] - .into_iter() - .map(|val| Reverse(val)) - .collect::>>(), - ); + min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); + // [endregion]{heapify} println!("\n輸入串列並建立小頂堆積後"); print_util::print_heap(min_heap.iter().map(|&val| val.0).collect()); } diff --git a/zh-hant/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs b/zh-hant/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs index 6331886a7..08922e4af 100644 --- a/zh-hant/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs +++ b/zh-hant/codes/rust/chapter_stack_and_queue/linkedlist_deque.rs @@ -6,9 +6,12 @@ use hello_algo_rust::include::print_util; +// [region]{import} use std::cell::RefCell; use std::rc::Rc; +// [endregion]{import} +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ pub struct ListNode { pub val: T, // 節點值 @@ -25,6 +28,7 @@ impl ListNode { })) } } +// [endregion]{doubly_list_node} /* 基於雙向鏈結串列實現的雙向佇列 */ #[allow(dead_code)] diff --git a/zh-hant/codes/rust/src/include/list_node.rs b/zh-hant/codes/rust/src/include/list_node.rs index 941e334c3..f48069811 100644 --- a/zh-hant/codes/rust/src/include/list_node.rs +++ b/zh-hant/codes/rust/src/include/list_node.rs @@ -4,20 +4,26 @@ * Author: codingonion (coderonion@gmail.com), rongyi (hiarongyi@gmail.com) */ +// [region]{import_cell} use std::cell::RefCell; +// [endregion]{import_cell} use std::collections::HashMap; +// [region]{import_rc} use std::rc::Rc; +// [endregion]{import_rc} +// [region]{list_node} #[derive(Debug)] pub struct ListNode { - pub val: T, - pub next: Option>>>, + pub val: T, // 節點值 + pub next: Option>>>, // 後繼節點指標 } impl ListNode { pub fn new(val: T) -> Rc>> { Rc::new(RefCell::new(ListNode { val, next: None })) } +// [endregion]{list_node} /* 將陣列反序列化為鏈結串列 */ pub fn arr_to_linked_list(array: &[T]) -> Option>>> @@ -54,4 +60,6 @@ impl ListNode { hashmap } +// [region]{list_node_end} } +// [endregion]{list_node_end} 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 d9c104267..578eabc7b 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 @@ -1,52 +1,24 @@ ```python title="" -class ListNode: - """鏈結串列節點類別""" - def __init__(self, val: int): - self.val: int = val # 節點值 - self.next: ListNode | None = None # 指向下一節點的引用 +[file]{modules/list_node}-[region]{list_node} ``` ```cpp title="" -/* 鏈結串列節點結構體 */ -struct ListNode { - int val; // 節點值 - ListNode *next; // 指向下一節點的指標 - ListNode(int x) : val(x), next(nullptr) {} // 建構子 -}; +[file]{utils/list_node.hpp}-[region]{list_node} ``` ```java title="" -/* 鏈結串列節點類別 */ -class ListNode { - int val; // 節點值 - ListNode next; // 指向下一節點的引用 - ListNode(int x) { val = x; } // 建構子 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```csharp title="" -/* 鏈結串列節點類別 */ -class ListNode(int x) { //建構子 - public int val = x; // 節點值 - public ListNode? next; // 指向下一節點的引用 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```go title="" -/* 鏈結串列節點結構體 */ -type ListNode struct { - Val int // 節點值 - Next *ListNode // 指向下一節點的指標 -} - -// NewListNode 建構子,建立一個新的鏈結串列 -func NewListNode(val int) *ListNode { - return &ListNode{ - Val: val, - Next: nil, - } -} +[file]{pkg/list_node}-[region]{list_node} ``` ```swift title="" @@ -62,84 +34,36 @@ class ListNode { ``` ```javascript title="" -/* 鏈結串列節點類別 */ -class ListNode { - constructor(val, next) { - this.val = (val === undefined ? 0 : val); // 節點值 - this.next = (next === undefined ? null : next); // 指向下一節點的引用 - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```typescript title="" -/* 鏈結串列節點類別 */ -class ListNode { - val: number; - next: ListNode | null; - constructor(val?: number, next?: ListNode | null) { - this.val = val === undefined ? 0 : val; // 節點值 - this.next = next === undefined ? null : next; // 指向下一節點的引用 - } -} +[file]{modules/ListNode}-[region]{list_node} ``` ```dart title="" -/* 鏈結串列節點類別 */ -class ListNode { - int val; // 節點值 - ListNode? next; // 指向下一節點的引用 - ListNode(this.val, [this.next]); // 建構子 -} +[file]{utils/list_node}-[region]{list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; -/* 鏈結串列節點類別 */ -#[derive(Debug)] -struct ListNode { - val: i32, // 節點值 - next: Option>>, // 指向下一節點的指標 -} +[file]{src/include/list_node}-[region]{import_cell} +[file]{src/include/list_node}-[region]{import_rc} + +[file]{src/include/list_node}-[region]{list_node} +[file]{src/include/list_node}-[region]{list_node_end} ``` ```c title="" -/* 鏈結串列節點結構體 */ -typedef struct ListNode { - int val; // 節點值 - struct ListNode *next; // 指向下一節點的指標 -} ListNode; - -/* 建構子 */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - return node; -} +[file]{utils/list_node.h}-[region]{list_node} ``` ```kotlin title="" -/* 鏈結串列節點類別 */ -// 建構子 -class ListNode(x: Int) { - val _val: Int = x // 節點值 - var next: ListNode? = null // 指向下一個節點的引用 -} +[file]{utils/ListNode}-[region]{list_node} +[file]{utils/ListNode}-[region]{list_node_end} ``` ```ruby title="" -# 鏈結串列節點類別 -class ListNode - attr_accessor :val # 節點值 - attr_accessor :next # 指向下一節點的引用 - - def initialize(val=0, next_node=nil) - @val = val - @next = next_node - end -end +[file]{utils/list_node}-[region]{list_node} ``` @@ -200,41 +124,19 @@ 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 # 指向前驅節點的引用 +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```cpp title="" -/* 雙向鏈結串列節點結構體 */ -struct ListNode { - int val; // 節點值 - ListNode *next; // 指向後繼節點的指標 - ListNode *prev; // 指向前驅節點的指標 - ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 建構子 -}; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```java title="" -/* 雙向鏈結串列節點類別 */ -class ListNode { - int val; // 節點值 - ListNode next; // 指向後繼節點的引用 - ListNode prev; // 指向前驅節點的引用 - ListNode(int x) { val = x; } // 建構子 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```csharp title="" -/* 雙向鏈結串列節點類別 */ -class ListNode(int x) { // 建構子 - public int val = x; // 節點值 - public ListNode? next; // 指向後繼節點的引用 - public ListNode? prev; // 指向前驅節點的引用 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```go title="" @@ -256,117 +158,35 @@ func NewDoublyListNode(val int) *DoublyListNode { ``` ```swift title="" -/* 雙向鏈結串列節點類別 */ -class ListNode { - var val: Int // 節點值 - var next: ListNode? // 指向後繼節點的引用 - var prev: ListNode? // 指向前驅節點的引用 - - init(x: Int) { // 建構子 - val = x - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // 指向前驅節點的引用 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```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; // 指向前驅節點的引用 - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```dart title="" -/* 雙向鏈結串列節點類別 */ -class ListNode { - int val; // 節點值 - ListNode? next; // 指向後繼節點的引用 - ListNode? prev; // 指向前驅節點的引用 - ListNode(this.val, [this.next, this.prev]); // 建構子 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```rust title="" -use std::rc::Rc; -use std::cell::RefCell; +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{import} -/* 雙向鏈結串列節點型別 */ -#[derive(Debug)] -struct ListNode { - val: i32, // 節點值 - next: Option>>, // 指向後繼節點的指標 - prev: Option>>, // 指向前驅節點的指標 -} - -/* 建構子 */ -impl ListNode { - fn new(val: i32) -> Self { - ListNode { - val, - next: None, - prev: None, - } - } -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```c title="" -/* 雙向鏈結串列節點結構體 */ -typedef struct ListNode { - int val; // 節點值 - struct ListNode *next; // 指向後繼節點的指標 - struct ListNode *prev; // 指向前驅節點的指標 -} ListNode; - -/* 建構子 */ -ListNode *newListNode(int val) { - ListNode *node; - node = (ListNode *) malloc(sizeof(ListNode)); - node->val = val; - node->next = NULL; - node->prev = NULL; - return node; -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```kotlin title="" -/* 雙向鏈結串列節點類別 */ -// 建構子 -class ListNode(x: Int) { - val _val: Int = x // 節點值 - var next: ListNode? = null // 指向後繼節點的引用 - var prev: ListNode? = null // 指向前驅節點的引用 -} +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` ```ruby title="" -# 雙向鏈結串列節點類別 -class ListNode - attr_accessor :val # 節點值 - attr_accessor :next # 指向後繼節點的引用 - attr_accessor :prev # 指向前驅節點的引用 - - def initialize(val=0, next_node=nil, prev_node=nil) - @val = val - @next = next_node - @prev = prev_node - end -end +[file]{chapter_stack_and_queue/linkedlist_deque}-[region]{doubly_list_node} ``` diff --git a/zh-hant/codes/snippets/chapter_heap/heap.md b/zh-hant/codes/snippets/chapter_heap/heap.md index c62de7af2..aa3e68167 100644 --- a/zh-hant/codes/snippets/chapter_heap/heap.md +++ b/zh-hant/codes/snippets/chapter_heap/heap.md @@ -1,256 +1,110 @@ ```python title="heap.py" -# 初始化小頂堆積 -min_heap, flag = [], 1 -# 初始化大頂堆積 -max_heap, flag = [], -1 +[file]{heap}-[region]{init} -# Python 的 heapq 模組預設實現小頂堆積 -# 考慮將“元素取負”後再入堆積,這樣就可以將大小關係顛倒,從而實現大頂堆積 -# 在本示例中,flag = 1 時對應小頂堆積,flag = -1 時對應大頂堆積 +[file]{heap}-[region]{push} -# 元素入堆積 -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) +[file]{heap}-[region]{peek} -# 獲取堆積頂元素 -peek: int = flag * max_heap[0] # 5 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_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 +[file]{heap}-[region]{size} -# 獲取堆積大小 -size: int = len(max_heap) +[file]{heap}-[region]{is_empty} -# 判斷堆積是否為空 -is_empty: bool = not max_heap - -# 輸入串列並建堆積 -min_heap: list[int] = [1, 3, 2, 5, 4] -heapq.heapify(min_heap) +[file]{heap}-[region]{heapify} ``` ```cpp title="heap.cpp" -/* 初始化堆積 */ -// 初始化小頂堆積 -priority_queue, greater> minHeap; -// 初始化大頂堆積 -priority_queue, less> maxHeap; +[file]{heap}-[region]{init} -/* 元素入堆積 */ -maxHeap.push(1); -maxHeap.push(3); -maxHeap.push(2); -maxHeap.push(5); -maxHeap.push(4); +[file]{heap}-[region]{push} -/* 獲取堆積頂元素 */ -int peek = maxHeap.top(); // 5 +[file]{heap}-[region]{peek} -/* 堆積頂元素出堆積 */ -// 出堆積元素會形成一個從大到小的序列 -maxHeap.pop(); // 5 -maxHeap.pop(); // 4 -maxHeap.pop(); // 3 -maxHeap.pop(); // 2 -maxHeap.pop(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 獲取堆積大小 */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* 判斷堆積是否為空 */ -bool isEmpty = maxHeap.empty(); +[file]{heap}-[region]{is_empty} -/* 輸入串列並建堆積 */ -vector input{1, 3, 2, 5, 4}; -minHeap = priority_queue, greater>(input.begin(), input.end()); +[file]{heap}-[region]{heapify} ``` ```java title="heap.java" -/* 初始化堆積 */ -// 初始化小頂堆積 -Queue minHeap = new PriorityQueue<>(); -// 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可) -Queue maxHeap = new PriorityQueue<>((a, b) -> b - a); +[file]{heap}-[region]{init} -/* 元素入堆積 */ -maxHeap.offer(1); -maxHeap.offer(3); -maxHeap.offer(2); -maxHeap.offer(5); -maxHeap.offer(4); +[file]{heap}-[region]{push} -/* 獲取堆積頂元素 */ -int peek = maxHeap.peek(); // 5 +[file]{heap}-[region]{peek} -/* 堆積頂元素出堆積 */ -// 出堆積元素會形成一個從大到小的序列 -peek = maxHeap.poll(); // 5 -peek = maxHeap.poll(); // 4 -peek = maxHeap.poll(); // 3 -peek = maxHeap.poll(); // 2 -peek = maxHeap.poll(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 獲取堆積大小 */ -int size = maxHeap.size(); +[file]{heap}-[region]{size} -/* 判斷堆積是否為空 */ -boolean isEmpty = maxHeap.isEmpty(); +[file]{heap}-[region]{is_empty} -/* 輸入串列並建堆積 */ -minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4)); +[file]{heap}-[region]{heapify} ``` ```csharp title="heap.cs" -/* 初始化堆積 */ -// 初始化小頂堆積 -PriorityQueue minHeap = new(); -// 初始化大頂堆積(使用 lambda 表示式修改 Comparer 即可) -PriorityQueue maxHeap = new(Comparer.Create((x, y) => y.CompareTo(x))); +[file]{heap}-[region]{init} -/* 元素入堆積 */ -maxHeap.Enqueue(1, 1); -maxHeap.Enqueue(3, 3); -maxHeap.Enqueue(2, 2); -maxHeap.Enqueue(5, 5); -maxHeap.Enqueue(4, 4); +[file]{heap}-[region]{push} -/* 獲取堆積頂元素 */ -int peek = maxHeap.Peek();//5 +[file]{heap}-[region]{peek} -/* 堆積頂元素出堆積 */ -// 出堆積元素會形成一個從大到小的序列 -peek = maxHeap.Dequeue(); // 5 -peek = maxHeap.Dequeue(); // 4 -peek = maxHeap.Dequeue(); // 3 -peek = maxHeap.Dequeue(); // 2 -peek = maxHeap.Dequeue(); // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 獲取堆積大小 */ -int size = maxHeap.Count; +[file]{heap}-[region]{size} -/* 判斷堆積是否為空 */ -bool isEmpty = maxHeap.Count == 0; +[file]{heap}-[region]{is_empty} -/* 輸入串列並建堆積 */ -minHeap = new PriorityQueue([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]); +[file]{heap}-[region]{heapify} ``` ```go title="heap.go" -// Go 語言中可以透過實現 heap.Interface 來構建整數大頂堆積 -// 實現 heap.Interface 需要同時實現 sort.Interface -type intHeap []any +[file]{heap}-[region]{int_heap} -// Push heap.Interface 的方法,實現推入元素到堆積 -func (h *intHeap) Push(x any) { - // Push 和 Pop 使用 pointer receiver 作為參數 - // 因為它們不僅會對切片的內容進行調整,還會修改切片的長度。 - *h = append(*h, x.(int)) -} - -// Pop heap.Interface 的方法,實現彈出堆積頂元素 -func (h *intHeap) Pop() any { - // 待出堆積元素存放在最後 - last := (*h)[len(*h)-1] - *h = (*h)[:len(*h)-1] - return last -} - -// Len sort.Interface 的方法 -func (h *intHeap) Len() int { - return len(*h) -} - -// Less sort.Interface 的方法 -func (h *intHeap) Less(i, j int) bool { - // 如果實現小頂堆積,則需要調整為小於號 - return (*h)[i].(int) > (*h)[j].(int) -} - -// Swap sort.Interface 的方法 -func (h *intHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] -} - -// Top 獲取堆積頂元素 -func (h *intHeap) Top() any { - return (*h)[0] -} - -/* Driver Code */ -func TestHeap(t *testing.T) { - /* 初始化堆積 */ - // 初始化大頂堆積 - maxHeap := &intHeap{} - heap.Init(maxHeap) - /* 元素入堆積 */ - // 呼叫 heap.Interface 的方法,來新增元素 - heap.Push(maxHeap, 1) - heap.Push(maxHeap, 3) - heap.Push(maxHeap, 2) - heap.Push(maxHeap, 4) - heap.Push(maxHeap, 5) - - /* 獲取堆積頂元素 */ - 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 - - /* 獲取堆積大小 */ - size := len(*maxHeap) - fmt.Printf("堆積元素數量為 %d\n", size) - - /* 判斷堆積是否為空 */ - isEmpty := len(*maxHeap) == 0 - fmt.Printf("堆積是否為空 %t\n", isEmpty) -} +[file]{heap_test}-[region]{test_heap} ``` ```swift title="heap.swift" -/* 初始化堆積 */ -// Swift 的 Heap 型別同時支持最大堆積和最小堆積,且需要引入 swift-collections -var heap = Heap() +[file]{heap}-[region]{import} -/* 元素入堆積 */ -heap.insert(1) -heap.insert(3) -heap.insert(2) -heap.insert(5) -heap.insert(4) +[file]{heap}-[region]{init} -/* 獲取堆積頂元素 */ -var peek = heap.max()! +[file]{heap}-[region]{push} -/* 堆積頂元素出堆積 */ -peek = heap.removeMax() // 5 -peek = heap.removeMax() // 4 -peek = heap.removeMax() // 3 -peek = heap.removeMax() // 2 -peek = heap.removeMax() // 1 +[file]{heap}-[region]{peek} -/* 獲取堆積大小 */ -let size = heap.count +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 判斷堆積是否為空 */ -let isEmpty = heap.isEmpty +[file]{heap}-[region]{size} -/* 輸入串列並建堆積 */ -let heap2 = Heap([1, 3, 2, 5, 4]) +[file]{heap}-[region]{is_empty} + +[file]{heap}-[region]{heapify} ``` ```javascript title="heap.js" @@ -266,41 +120,25 @@ let heap2 = Heap([1, 3, 2, 5, 4]) ``` ```rust title="heap.rs" -use std::collections::BinaryHeap; -use std::cmp::Reverse; +[file]{heap}-[region]{import} -/* 初始化堆積 */ -// 初始化小頂堆積 -let mut min_heap = BinaryHeap::>::new(); -// 初始化大頂堆積 -let mut max_heap = BinaryHeap::new(); +[file]{heap}-[region]{init} -/* 元素入堆積 */ -max_heap.push(1); -max_heap.push(3); -max_heap.push(2); -max_heap.push(5); -max_heap.push(4); +[file]{heap}-[region]{push} -/* 獲取堆積頂元素 */ -let peek = max_heap.peek().unwrap(); // 5 +[file]{heap}-[region]{peek} -/* 堆積頂元素出堆積 */ -// 出堆積元素會形成一個從大到小的序列 -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 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 獲取堆積大小 */ -let size = max_heap.len(); +[file]{heap}-[region]{size} -/* 判斷堆積是否為空 */ -let is_empty = max_heap.is_empty(); +[file]{heap}-[region]{is_empty} -/* 輸入串列並建堆積 */ -let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]); +[file]{heap}-[region]{heapify} ``` ```c title="heap.c" @@ -308,38 +146,23 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse ``` ```kotlin title="heap.kt" -/* 初始化堆積 */ -// 初始化小頂堆積 -var minHeap = PriorityQueue() -// 初始化大頂堆積(使用 lambda 表示式修改 Comparator 即可) -val maxHeap = PriorityQueue { a: Int, b: Int -> b - a } +[file]{heap}-[region]{init} -/* 元素入堆積 */ -maxHeap.offer(1) -maxHeap.offer(3) -maxHeap.offer(2) -maxHeap.offer(5) -maxHeap.offer(4) +[file]{heap}-[region]{push} -/* 獲取堆積頂元素 */ -var peek = maxHeap.peek() // 5 +[file]{heap}-[region]{peek} -/* 堆積頂元素出堆積 */ -// 出堆積元素會形成一個從大到小的序列 -peek = maxHeap.poll() // 5 -peek = maxHeap.poll() // 4 -peek = maxHeap.poll() // 3 -peek = maxHeap.poll() // 2 -peek = maxHeap.poll() // 1 +[file]{heap}-[region]{pop_1} +[file]{heap}-[region]{pop_2} +[file]{heap}-[region]{pop_3} +[file]{heap}-[region]{pop_4} +[file]{heap}-[region]{pop_5} -/* 獲取堆積大小 */ -val size = maxHeap.size +[file]{heap}-[region]{size} -/* 判斷堆積是否為空 */ -val isEmpty = maxHeap.isEmpty() +[file]{heap}-[region]{is_empty} -/* 輸入串列並建堆積 */ -minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4)) +[file]{heap}-[region]{heapify} ``` ```ruby title="heap.rb" diff --git a/zh-hant/codes/swift/chapter_heap/heap.swift b/zh-hant/codes/swift/chapter_heap/heap.swift index c24e20253..469e1d97a 100644 --- a/zh-hant/codes/swift/chapter_heap/heap.swift +++ b/zh-hant/codes/swift/chapter_heap/heap.swift @@ -4,58 +4,76 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{import} import HeapModule +// [endregion]{import} import utils -func testPush(heap: inout Heap, val: Int) { - heap.insert(val) - print("\n元素 \(val) 入堆積後\n") - PrintUtil.printHeap(queue: heap.unordered) -} - -func testPop(heap: inout Heap) { - let val = heap.removeMax() - print("\n堆積頂元素 \(val) 出堆積後\n") - PrintUtil.printHeap(queue: heap.unordered) -} - @main enum _Heap { /* Driver Code */ static func main() { + // [region]{init} /* 初始化堆積 */ // Swift 的 Heap 型別同時支持最大堆積和最小堆積 var heap = Heap() + // [endregion]{init} + // [region]{push} /* 元素入堆積 */ - testPush(heap: &heap, val: 1) - testPush(heap: &heap, val: 3) - testPush(heap: &heap, val: 2) - testPush(heap: &heap, val: 5) - testPush(heap: &heap, val: 4) + heap.insert(1) + heap.insert(3) + heap.insert(2) + heap.insert(5) + heap.insert(4) + // [endregion]{push} + PrintUtil.printHeap(queue: heap.unordered) + // [region]{peek} /* 獲取堆積頂元素 */ - let peek = heap.max() + var peek = heap.max() + // [endregion]{peek} print("\n堆積頂元素為 \(peek!)\n") + // [region]{pop_1} /* 堆積頂元素出堆積 */ - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) - testPop(heap: &heap) + peek = heap.removeMax() // 5 + // [endregion]{pop_1} + print(peek!) + // [region]{pop_2} + peek = heap.removeMax() // 4 + // [endregion]{pop_2} + print(peek!) + // [region]{pop_3} + peek = heap.removeMax() // 3 + // [endregion]{pop_3} + print(peek!) + // [region]{pop_4} + peek = heap.removeMax() // 2 + // [endregion]{pop_4} + print(peek!) + // [region]{pop_5} + peek = heap.removeMax() // 1 + // [endregion]{pop_5} + print(peek!) + // [region]{size} /* 獲取堆積大小 */ let size = heap.count + // [endregion]{size} print("\n堆積元素數量為 \(size)\n") + // [region]{is_empty} /* 判斷堆積是否為空 */ let isEmpty = heap.isEmpty + // [endregion]{is_empty} print("\n堆積是否為空 \(isEmpty)\n") + // [region]{heapify} /* 輸入串列並建堆積 */ // 時間複雜度為 O(n) ,而非 O(nlogn) let heap2 = Heap([1, 3, 2, 5, 4]) + // [endregion]{heapify} print("\n輸入串列並建立堆積後") PrintUtil.printHeap(queue: heap2.unordered) } diff --git a/zh-hant/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift b/zh-hant/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift index fa2cd2b39..cfab43f19 100644 --- a/zh-hant/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift +++ b/zh-hant/codes/swift/chapter_stack_and_queue/linkedlist_deque.swift @@ -4,6 +4,7 @@ * Author: nuomi1 (nuomi1@qq.com) */ +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ class ListNode { var val: Int // 節點值 @@ -14,6 +15,7 @@ class ListNode { self.val = val } } +// [endregion]{doubly_list_node} /* 基於雙向鏈結串列實現的雙向佇列 */ class LinkedListDeque { 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..f5f2ded62 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 @@ -4,10 +4,11 @@ * Author: Zhuo Qinyue (1403450829@qq.com) */ +// [region]{doubly_list_node} /* 雙向鏈結串列節點 */ class ListNode { - prev: ListNode; // 前驅節點引用 (指標) - next: ListNode; // 後繼節點引用 (指標) + prev: ListNode | null; // 前驅節點引用 (指標) + next: ListNode | null; // 後繼節點引用 (指標) val: number; // 節點值 constructor(val: number) { @@ -16,6 +17,7 @@ class ListNode { this.prev = null; } } +// [endregion]{doubly_list_node} /* 基於雙向鏈結串列實現的雙向佇列 */ class LinkedListDeque { diff --git a/zh-hant/codes/typescript/modules/ListNode.ts b/zh-hant/codes/typescript/modules/ListNode.ts index 63c1f57e9..873ec4873 100644 --- a/zh-hant/codes/typescript/modules/ListNode.ts +++ b/zh-hant/codes/typescript/modules/ListNode.ts @@ -4,15 +4,17 @@ * Author: Justin (xiefahit@gmail.com) */ +// [region]{list_node} /* 鏈結串列節點 */ 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; } } +// [endregion]{list_node} /* 將陣列反序列化為鏈結串列 */ function arrToLinkedList(arr: number[]): ListNode | null {