Cite demo-source regions for heap operations and the linked-list node classes (#2036)

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 <noreply@anthropic.com>
This commit is contained in:
Yudong Jin
2026-11-16 05:23:41 +08:00
committed by GitHub
parent eeb8a3b790
commit bcd86fc1ed
210 changed files with 3061 additions and 4177 deletions

View File

@@ -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) {

View File

@@ -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) {

View File

@@ -6,59 +6,75 @@
#include "../utils/common.hpp"
void testPush(priority_queue<int> &heap, int val) {
heap.push(val); // 元素入堆
cout << "\n元素 " << val << " 入堆后" << endl;
printHeap(heap);
}
void testPop(priority_queue<int> &heap) {
int val = heap.top();
heap.pop();
cout << "\n堆顶元素 " << val << " 出堆后" << endl;
printHeap(heap);
}
/* Driver Code */
int main() {
// [region]{init}
/* 初始化堆 */
// 初始化小顶堆
// priority_queue<int, vector<int>, greater<int>> minHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
// 初始化大顶堆
priority_queue<int, vector<int>, less<int>> 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<int> input{1, 3, 2, 5, 4};
priority_queue<int, vector<int>, greater<int>> minHeap(input.begin(), input.end());
minHeap = priority_queue<int, vector<int>, greater<int>>(input.begin(), input.end());
// [endregion]{heapify}
cout << "输入列表并建立小顶堆后" << endl;
printHeap(minHeap);

View File

@@ -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 {

View File

@@ -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<int> list) {

View File

@@ -7,57 +7,72 @@
namespace hello_algo.chapter_heap;
public class heap {
void TestPush(PriorityQueue<int, int> heap, int val) {
heap.Enqueue(val, val); // 元素入堆
Console.WriteLine($"\n元素 {val} 入堆后\n");
PrintUtil.PrintHeap(heap);
}
void TestPop(PriorityQueue<int, int> heap) {
int val = heap.Dequeue(); // 堆顶元素出堆
Console.WriteLine($"\n堆顶元素 {val} 出堆后\n");
PrintUtil.PrintHeap(heap);
}
[Test]
public void Test() {
// [region]{init}
/* 初始化堆 */
// 初始化小顶堆
PriorityQueue<int, int> minHeap = new();
// 初始化大顶堆(使用 lambda 表达式修改 Comparer 即可)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.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<int, int>(list.Select(x => (x, x)));
minHeap = new PriorityQueue<int, int>([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]);
// [endregion]{heapify}
Console.WriteLine("输入列表并建立小顶堆后");
PrintUtil.PrintHeap(minHeap);
}

View File

@@ -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 {

View File

@@ -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}

View File

@@ -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 {

View File

@@ -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<int> list) {

View File

@@ -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}

View File

@@ -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) {
/* 初始化堆 */
// 初始化大顶堆

View File

@@ -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

View File

@@ -10,56 +10,73 @@ import utils.*;
import java.util.*;
public class heap {
public static void testPush(Queue<Integer> heap, int val) {
heap.offer(val); // 元素入堆
System.out.format("\n元素 %d 入堆后\n", val);
PrintUtil.printHeap(heap);
}
public static void testPop(Queue<Integer> heap) {
int val = heap.poll(); // 堆顶元素出堆
System.out.format("\n堆顶元素 %d 出堆后\n", val);
PrintUtil.printHeap(heap);
}
public static void main(String[] args) {
// [region]{init}
/* 初始化堆 */
// 初始化小顶堆
Queue<Integer> minHeap = new PriorityQueue<>();
// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可)
Queue<Integer> 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);
}

View File

@@ -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 {

View File

@@ -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}

View File

@@ -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 {

View File

@@ -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) {

View File

@@ -9,58 +9,74 @@ package chapter_heap
import utils.printHeap
import java.util.*
fun testPush(heap: Queue<Int>, _val: Int) {
heap.offer(_val) // 元素入堆
print("\n元素 $_val 入堆后\n")
printHeap(heap)
}
fun testPop(heap: Queue<Int>) {
val _val = heap.poll() // 堆顶元素出堆
print("\n堆顶元素 $_val 出堆后\n")
printHeap(heap)
}
/* Driver Code */
fun main() {
// [region]{init}
/* 初始化堆 */
// 初始化小顶堆
var minHeap = PriorityQueue<Int>()
// 初始化大顶堆(使用 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<Int?>(1, 3, 2, 5, 4))
// [endregion]{heapify}
println("\n输入列表并建立小顶堆后")
printHeap(minHeap)
}

View File

@@ -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")
}
}

View File

@@ -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
}
}
}
// [region]{list_node_end}
}
// [endregion]{list_node_end}

View File

@@ -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)

View File

@@ -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:

View File

@@ -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:

View File

@@ -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

View File

@@ -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)

View File

@@ -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<i32>, 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<i32>) {
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::<Vec<Reverse<i32>>>(),
);
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());
}

View File

@@ -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<T> {
pub val: T, // 节点值
@@ -25,6 +28,7 @@ impl<T> ListNode<T> {
}))
}
}
// [endregion]{doubly_list_node}
/* 基于双向链表实现的双向队列 */
#[allow(dead_code)]

View File

@@ -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<T> {
pub val: T,
pub next: Option<Rc<RefCell<ListNode<T>>>>,
pub val: T, // 节点值
pub next: Option<Rc<RefCell<ListNode<T>>>>, // 后继节点指针
}
impl<T> ListNode<T> {
pub fn new(val: T) -> Rc<RefCell<ListNode<T>>> {
Rc::new(RefCell::new(ListNode { val, next: None }))
}
// [endregion]{list_node}
/* 将数组反序列化为链表 */
pub fn arr_to_linked_list(array: &[T]) -> Option<Rc<RefCell<ListNode<T>>>>
@@ -54,4 +60,6 @@ impl<T> ListNode<T> {
hashmap
}
// [region]{list_node_end}
}
// [endregion]{list_node_end}

View File

@@ -1,52 +1,24 @@
<!-- [snippet]{list_node_class} -->
```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<Rc<RefCell<ListNode>>>, // 指向下一节点的指针
}
[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}
```
<!-- [snippet]{init_linked_list} -->
@@ -200,41 +124,19 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2
<!-- [snippet]{doubly_list_node_class} -->
```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<Rc<RefCell<ListNode>>>, // 指向后继节点的指针
prev: Option<Rc<RefCell<ListNode>>>, // 指向前驱节点的指针
}
/* 构造函数 */
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}
```

View File

@@ -1,256 +1,110 @@
<!-- [snippet]{heap_operations} -->
```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<int, vector<int>, greater<int>> minHeap;
// 初始化大顶堆
priority_queue<int, vector<int>, less<int>> 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<int> input{1, 3, 2, 5, 4};
minHeap = priority_queue<int, vector<int>, greater<int>>(input.begin(), input.end());
[file]{heap}-[region]{heapify}
```
```java title="heap.java"
/* 初始化堆 */
// 初始化小顶堆
Queue<Integer> minHeap = new PriorityQueue<>();
// 初始化大顶堆(使用 lambda 表达式修改 Comparator 即可)
Queue<Integer> 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<int, int> minHeap = new();
// 初始化大顶堆(使用 lambda 表达式修改 Comparer 即可)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.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<int, int>([(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<Int>()
[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::<Reverse<i32>>::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<Int>()
// 初始化大顶堆(使用 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"

View File

@@ -4,58 +4,76 @@
* Author: nuomi1 (nuomi1@qq.com)
*/
// [region]{import}
import HeapModule
// [endregion]{import}
import utils
func testPush(heap: inout Heap<Int>, val: Int) {
heap.insert(val)
print("\n元素 \(val) 入堆后\n")
PrintUtil.printHeap(queue: heap.unordered)
}
func testPop(heap: inout Heap<Int>) {
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<Int>()
// [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)
}

View File

@@ -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 {

View File

@@ -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 {

View File

@@ -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 {

View File

@@ -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) {

View File

@@ -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) {

View File

@@ -6,59 +6,75 @@
#include "../utils/common.hpp"
void testPush(priority_queue<int> &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<int> &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<int, vector<int>, greater<int>> minHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
// Initialize a max heap
priority_queue<int, vector<int>, less<int>> 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<int> input{1, 3, 2, 5, 4};
priority_queue<int, vector<int>, greater<int>> minHeap(input.begin(), input.end());
minHeap = priority_queue<int, vector<int>, greater<int>>(input.begin(), input.end());
// [endregion]{heapify}
cout << "After building a min heap from the input list:" << endl;
printHeap(minHeap);

View File

@@ -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 {

View File

@@ -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<int> list) {

View File

@@ -7,57 +7,72 @@
namespace hello_algo.chapter_heap;
public class heap {
void TestPush(PriorityQueue<int, int> 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<int, int> 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<int, int> minHeap = new();
// Initialize a max heap (use a lambda expression to customize the Comparer)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.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<int, int>(list.Select(x => (x, x)));
minHeap = new PriorityQueue<int, int>([(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);
}

View File

@@ -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 {

View File

@@ -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}

View File

@@ -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 {

View File

@@ -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<int> list) {

View File

@@ -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}

View File

@@ -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

View File

@@ -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

View File

@@ -10,56 +10,73 @@ import utils.*;
import java.util.*;
public class heap {
public static void testPush(Queue<Integer> 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<Integer> 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<Integer> minHeap = new PriorityQueue<>();
// Initialize a max heap by supplying a lambda expression as the Comparator
Queue<Integer> 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);
}

View File

@@ -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 {

View File

@@ -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}

View File

@@ -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 {

View File

@@ -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) {

View File

@@ -9,58 +9,74 @@ package chapter_heap
import utils.printHeap
import java.util.*
fun testPush(heap: Queue<Int>, _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<Int>) {
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<Int>()
// 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<Int?>(1, 3, 2, 5, 4))
// [endregion]{heapify}
println("\nAfter building a min heap from the input list:")
printHeap(minHeap)
}

View File

@@ -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")
}
}

View File

@@ -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
}
}
}
// [region]{list_node_end}
}
// [endregion]{list_node_end}

View File

@@ -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)

View File

@@ -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:

View File

@@ -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:

View File

@@ -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

View File

@@ -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)

View File

@@ -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<i32>, 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<i32>) {
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::<Vec<Reverse<i32>>>(),
);
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());
}

View File

@@ -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<T> {
pub val: T, // Node value
@@ -25,6 +28,7 @@ impl<T> ListNode<T> {
}))
}
}
// [endregion]{doubly_list_node}
/* Deque implemented with a doubly linked list */
#[allow(dead_code)]

View File

@@ -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<T> {
pub val: T,
pub next: Option<Rc<RefCell<ListNode<T>>>>,
pub val: T, // Node value
pub next: Option<Rc<RefCell<ListNode<T>>>>, // Pointer to the next node
}
impl<T> ListNode<T> {
pub fn new(val: T) -> Rc<RefCell<ListNode<T>>> {
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<Rc<RefCell<ListNode<T>>>>
@@ -54,4 +60,6 @@ impl<T> ListNode<T> {
hashmap
}
// [region]{list_node_end}
}
// [endregion]{list_node_end}

View File

@@ -1,52 +1,24 @@
<!-- [snippet]{list_node_class} -->
```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<Rc<RefCell<ListNode>>>, // 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}
```
<!-- [snippet]{init_linked_list} -->
@@ -200,41 +124,19 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2
<!-- [snippet]{doubly_list_node_class} -->
```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<Rc<RefCell<ListNode>>>, // Pointer to the successor
prev: Option<Rc<RefCell<ListNode>>>, // 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}
```

View File

@@ -1,256 +1,110 @@
<!-- [snippet]{heap_operations} -->
```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<int, vector<int>, greater<int>> minHeap;
// Initialize a max heap
priority_queue<int, vector<int>, less<int>> 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<int> input{1, 3, 2, 5, 4};
minHeap = priority_queue<int, vector<int>, greater<int>>(input.begin(), input.end());
[file]{heap}-[region]{heapify}
```
```java title="heap.java"
/* Initialize a heap */
// Initialize a min heap
Queue<Integer> minHeap = new PriorityQueue<>();
// Initialize a max heap by changing the Comparator with a lambda expression
Queue<Integer> 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<int, int> minHeap = new();
// Initialize a max heap by changing the Comparer with a lambda expression
PriorityQueue<int, int> maxHeap = new(Comparer<int>.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<int, int>([(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<Int>()
[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::<Reverse<i32>>::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<Int>()
// 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"

View File

@@ -4,58 +4,76 @@
* Author: nuomi1 (nuomi1@qq.com)
*/
// [region]{import}
import HeapModule
// [endregion]{import}
import utils
func testPush(heap: inout Heap<Int>, val: Int) {
heap.insert(val)
print("\nAfter inserting element \(val) into the heap:\n")
PrintUtil.printHeap(queue: heap.unordered)
}
func testPop(heap: inout Heap<Int>) {
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<Int>()
// [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)
}

View File

@@ -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 {

View File

@@ -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 {

View File

@@ -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 {

View File

@@ -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) {

View File

@@ -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) {

View File

@@ -6,59 +6,75 @@
#include "../utils/common.hpp"
void testPush(priority_queue<int> &heap, int val) {
heap.push(val); // ヒープに要素を挿入する
cout << "\n要素 " << val << " をヒープに挿入した後" << endl;
printHeap(heap);
}
void testPop(priority_queue<int> &heap) {
int val = heap.top();
heap.pop();
cout << "\nヒープの先頭要素 " << val << " を取り出した後" << endl;
printHeap(heap);
}
/* 実行用コード */
int main() {
// [region]{init}
/* ヒープを初期化する */
// 最小ヒープを初期化する
// priority_queue<int, vector<int>, greater<int>> minHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
// 最大ヒープを初期化する
priority_queue<int, vector<int>, less<int>> 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<int> input{1, 3, 2, 5, 4};
priority_queue<int, vector<int>, greater<int>> minHeap(input.begin(), input.end());
minHeap = priority_queue<int, vector<int>, greater<int>>(input.begin(), input.end());
// [endregion]{heapify}
cout << "リストを入力して最小ヒープを構築した後" << endl;
printHeap(minHeap);

View File

@@ -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 {

View File

@@ -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<int> list) {

View File

@@ -7,57 +7,72 @@
namespace hello_algo.chapter_heap;
public class heap {
void TestPush(PriorityQueue<int, int> heap, int val) {
heap.Enqueue(val, val); // ヒープに要素を挿入する
Console.WriteLine($"\n要素 {val} をヒープに挿入した後\n");
PrintUtil.PrintHeap(heap);
}
void TestPop(PriorityQueue<int, int> heap) {
int val = heap.Dequeue(); // ヒープの先頭要素を取り出す
Console.WriteLine($"\nヒープの先頭要素 {val} を取り出した後\n");
PrintUtil.PrintHeap(heap);
}
[Test]
public void Test() {
// [region]{init}
/* ヒープを初期化する */
// 最小ヒープを初期化する
PriorityQueue<int, int> minHeap = new();
// 最大ヒープを初期化する(ラムダ式で Comparer を変更すればよい)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.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<int, int>(list.Select(x => (x, x)));
minHeap = new PriorityQueue<int, int>([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]);
// [endregion]{heapify}
Console.WriteLine("リストを入力して最小ヒープを構築した後");
PrintUtil.PrintHeap(minHeap);
}

View File

@@ -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 {

View File

@@ -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}

View File

@@ -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 {

View File

@@ -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<int> list) {

View File

@@ -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}

View File

@@ -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) {
/* ヒープを初期化する */
// 最大ヒープを初期化する

View File

@@ -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 {
// 連結リストのダミーの先頭ノード

View File

@@ -10,56 +10,73 @@ import utils.*;
import java.util.*;
public class heap {
public static void testPush(Queue<Integer> heap, int val) {
heap.offer(val); // ヒープに要素を挿入する
System.out.format("\n要素 %d をヒープに挿入した後\n", val);
PrintUtil.printHeap(heap);
}
public static void testPop(Queue<Integer> heap) {
int val = heap.poll(); // ヒープの先頭要素を取り出す
System.out.format("\nヒープの先頭要素 %d を取り出した後\n", val);
PrintUtil.printHeap(heap);
}
public static void main(String[] args) {
// [region]{init}
/* ヒープを初期化する */
// 最小ヒープを初期化する
Queue<Integer> minHeap = new PriorityQueue<>();
// 最大ヒープを初期化する(ラムダ式で Comparator を変更すればよい)
Queue<Integer> 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);
}

View File

@@ -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 {

View File

@@ -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}

View File

@@ -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 {

View File

@@ -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) {

View File

@@ -9,58 +9,74 @@ package chapter_heap
import utils.printHeap
import java.util.*
fun testPush(heap: Queue<Int>, _val: Int) {
heap.offer(_val) // ヒープに要素を挿入する
print("\n要素 $_val をヒープに挿入した後\n")
printHeap(heap)
}
fun testPop(heap: Queue<Int>) {
val _val = heap.poll() // ヒープの先頭要素を取り出す
print("\nヒープの先頭要素 $_val を取り出した後\n")
printHeap(heap)
}
/* 実行用コード */
fun main() {
// [region]{init}
/* ヒープを初期化する */
// 最小ヒープを初期化する
var minHeap = PriorityQueue<Int>()
// 最大ヒープを初期化する(ラムダ式で 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<Int?>(1, 3, 2, 5, 4))
// [endregion]{heapify}
println("\nリストを入力して最小ヒープを構築した後")
printHeap(minHeap)
}

View File

@@ -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")
}
}

View File

@@ -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
}
}
}
// [region]{list_node_end}
}
// [endregion]{list_node_end}

View File

@@ -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)

View File

@@ -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:

View File

@@ -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:

View File

@@ -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

View File

@@ -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)

View File

@@ -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<i32>, 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<i32>) {
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::<Vec<Reverse<i32>>>(),
);
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());
}

View File

@@ -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<T> {
pub val: T, // ノードの値
@@ -25,6 +28,7 @@ impl<T> ListNode<T> {
}))
}
}
// [endregion]{doubly_list_node}
/* 双方向連結リストで実装した両端キュー */
#[allow(dead_code)]

View File

@@ -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<T> {
pub val: T,
pub next: Option<Rc<RefCell<ListNode<T>>>>,
pub val: T, // ノードの値
pub next: Option<Rc<RefCell<ListNode<T>>>>, // 後続ノードへのポインタ
}
impl<T> ListNode<T> {
pub fn new(val: T) -> Rc<RefCell<ListNode<T>>> {
Rc::new(RefCell::new(ListNode { val, next: None }))
}
// [endregion]{list_node}
/* 配列をデシリアライズして連結リストにする */
pub fn arr_to_linked_list(array: &[T]) -> Option<Rc<RefCell<ListNode<T>>>>
@@ -54,4 +60,6 @@ impl<T> ListNode<T> {
hashmap
}
// [region]{list_node_end}
}
// [endregion]{list_node_end}

View File

@@ -1,52 +1,24 @@
<!-- [snippet]{list_node_class} -->
```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<Rc<RefCell<ListNode>>>, // 次のノードへのポインタ
}
[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}
```
<!-- [snippet]{init_linked_list} -->
@@ -200,41 +124,19 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2
<!-- [snippet]{doubly_list_node_class} -->
```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<Rc<RefCell<ListNode>>>, // 後続ノードへのポインタ
prev: Option<Rc<RefCell<ListNode>>>, // 先行ノードへのポインタ
}
/* コンストラクタ */
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}
```

Some files were not shown because too many files have changed in this diff Show More