Correct and unify doc snippets; fix errors in the demo sources (#2039)

Code snippets in the book are corrected and unified across languages and
kept as literal blocks in the snippet files. The demo sources keep their
#2033 form, with fixes only for real errors: wrong code, wrong printed
labels, comments that contradict the code, and typos. en/ja/ko demos are
rendered from the reviewed code dictionaries (krahets/hello-algo-workspace#78).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Yudong Jin
2026-11-23 15:29:13 +08:00
committed by GitHub
parent 53611a0ae9
commit 4fd605c502
277 changed files with 6296 additions and 5742 deletions

View File

@@ -1,117 +1,117 @@
/**
* File: array.c
* Created Time: 2022-12-20
* Author: MolDuM (moldum@163.com)
*/
#include "../utils/common.h"
/* 随机访问元素 */
int randomAccess(int *nums, int size) {
// 在区间 [0, size) 中随机抽取一个数字
int randomIndex = rand() % size;
// 获取并返回随机元素
int randomNum = nums[randomIndex];
return randomNum;
}
/* 扩展数组长度 */
int *extend(int *nums, int size, int enlarge) {
// 初始化一个扩展长度后的数组
int *res = (int *)malloc(sizeof(int) * (size + enlarge));
// 将原数组中的所有元素复制到新数组
for (int i = 0; i < size; i++) {
res[i] = nums[i];
}
// 初始化扩展后的空间
for (int i = size; i < size + enlarge; i++) {
res[i] = 0;
}
// 返回扩展后的新数组
return res;
}
/* 在数组的索引 index 处插入元素 num */
void insert(int *nums, int size, int num, int index) {
// 把索引 index 以及之后的所有元素向后移动一位
for (int i = size - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// 将 num 赋给 index 处的元素
nums[index] = num;
}
/* 删除索引 index 处的元素 */
// 注意:stdio.h 占用了 remove 关键词
void removeItem(int *nums, int size, int index) {
// 把索引 index 之后的所有元素向前移动一位
for (int i = index; i < size - 1; i++) {
nums[i] = nums[i + 1];
}
}
/* 遍历数组 */
void traverse(int *nums, int size) {
int count = 0;
// 通过索引遍历数组
for (int i = 0; i < size; i++) {
count += nums[i];
}
}
/* 在数组中查找指定元素 */
int find(int *nums, int size, int target) {
for (int i = 0; i < size; i++) {
if (nums[i] == target)
return i;
}
return -1;
}
/* Driver Code */
int main() {
/* 初始化随机种子(只需执行一次) */
srand((unsigned)time(NULL));
/* 初始化数组 */
int size = 5;
int arr[5];
printf("数组 arr = ");
printArray(arr, size);
int nums[] = {1, 3, 2, 5, 4};
printf("数组 nums = ");
printArray(nums, size);
/* 随机访问 */
int randomNum = randomAccess(nums, size);
printf("在 nums 中获取随机元素 %d", randomNum);
/* 长度扩展 */
int enlarge = 3;
int *res = extend(nums, size, enlarge);
size += enlarge;
printf("将数组长度扩展至 8 ,得到 nums = ");
printArray(res, size);
/* 插入元素 */
insert(res, size, 6, 3);
printf("在索引 3 处插入数字 6 ,得到 nums = ");
printArray(res, size);
/* 删除元素 */
removeItem(res, size, 2);
printf("删除索引 2 处的元素,得到 nums = ");
printArray(res, size);
/* 遍历数组 */
traverse(res, size);
/* 查找元素 */
int index = find(res, size, 3);
printf("在 res 中查找元素 3 ,得到索引 = %d\n", index);
/* 释放内存 */
free(res);
return 0;
}
/**
* File: array.c
* Created Time: 2022-12-20
* Author: MolDuM (moldum@163.com)
*/
#include "../utils/common.h"
/* 随机访问元素 */
int randomAccess(int *nums, int size) {
// 在区间 [0, size) 中随机抽取一个数字
int randomIndex = rand() % size;
// 获取并返回随机元素
int randomNum = nums[randomIndex];
return randomNum;
}
/* 扩展数组长度 */
int *extend(int *nums, int size, int enlarge) {
// 初始化一个扩展长度后的数组
int *res = (int *)malloc(sizeof(int) * (size + enlarge));
// 将原数组中的所有元素复制到新数组
for (int i = 0; i < size; i++) {
res[i] = nums[i];
}
// 初始化扩展后的空间
for (int i = size; i < size + enlarge; i++) {
res[i] = 0;
}
// 返回扩展后的新数组
return res;
}
/* 在数组的索引 index 处插入元素 num */
void insert(int *nums, int size, int num, int index) {
// 把索引 index 以及之后的所有元素向后移动一位
for (int i = size - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// 将 num 赋给 index 处的元素
nums[index] = num;
}
/* 删除索引 index 处的元素 */
// 注意:stdio.h 占用了 remove 关键词
void removeItem(int *nums, int size, int index) {
// 把索引 index 之后的所有元素向前移动一位
for (int i = index; i < size - 1; i++) {
nums[i] = nums[i + 1];
}
}
/* 遍历数组 */
void traverse(int *nums, int size) {
int count = 0;
// 通过索引遍历数组
for (int i = 0; i < size; i++) {
count += nums[i];
}
}
/* 在数组中查找指定元素 */
int find(int *nums, int size, int target) {
for (int i = 0; i < size; i++) {
if (nums[i] == target)
return i;
}
return -1;
}
/* Driver Code */
int main() {
/* 初始化随机种子(只需执行一次) */
srand((unsigned)time(NULL));
/* 初始化数组 */
int size = 5;
int arr[5] = {0};
printf("数组 arr = ");
printArray(arr, size);
int nums[] = {1, 3, 2, 5, 4};
printf("数组 nums = ");
printArray(nums, size);
/* 随机访问 */
int randomNum = randomAccess(nums, size);
printf("在 nums 中获取随机元素 %d", randomNum);
/* 长度扩展 */
int enlarge = 3;
int *res = extend(nums, size, enlarge);
size += enlarge;
printf("将数组长度扩展至 8 ,得到 nums = ");
printArray(res, size);
/* 插入元素 */
insert(res, size, 6, 3);
printf("在索引 3 处插入数字 6 ,得到 nums = ");
printArray(res, size);
/* 删除元素 */
removeItem(res, size, 2);
printf("删除索引 2 处的元素,得到 nums = ");
printArray(res, size);
/* 遍历数组 */
traverse(res, size);
/* 查找元素 */
int index = find(res, size, 3);
printf("在 res 中查找元素 3 ,得到索引 = %d\n", index);
/* 释放内存 */
free(res);
return 0;
}

View File

@@ -182,7 +182,7 @@ int main() {
int peekFirstNum = peekFirst(deque);
printf("队首元素 peekFirst = %d\r\n", peekFirstNum);
int peekLastNum = peekLast(deque);
printf("队首元素 peekLast = %d\r\n", peekLastNum);
printf("队尾元素 peekLast = %d\r\n", peekLastNum);
/* 元素入队 */
pushLast(deque, 4);

View File

@@ -14,7 +14,7 @@ extern "C" {
/* 链表节点结构体 */
typedef struct ListNode {
int val; // 节点值
struct ListNode *next; // 指向下一节点的引用
struct ListNode *next; // 指向下一节点的指针
} ListNode;
/* 构造函数,初始化一个新节点 */

View File

@@ -18,7 +18,7 @@ int randomAccess(int *nums, int size) {
/* 扩展数组长度 */
int *extend(int *nums, int size, int enlarge) {
// 初始化一个扩展长度后的数组
int *res = new int[size + enlarge];
int *res = new int[size + enlarge]{};
// 将原数组中的所有元素复制到新数组
for (int i = 0; i < size; i++) {
res[i] = nums[i];
@@ -69,7 +69,7 @@ int find(int *nums, int size, int target) {
int main() {
/* 初始化数组 */
int size = 5;
int *arr = new int[size];
int *arr = new int[size]{};
cout << "数组 arr = ";
printArray(arr, size);

View File

@@ -36,6 +36,5 @@ void main() {
print("\n单独遍历键 Key");
map.keys.forEach((key) => print(key));
print("\n单独遍历值 Value");
map.forEach((key, value) => print("$value"));
map.values.forEach((value) => print(value));
}

View File

@@ -9,7 +9,7 @@ import '../utils/tree_node.dart';
void main() {
/* 初始化二叉树 */
// 舒适化节点
// 初始化节点
TreeNode n1 = TreeNode(1);
TreeNode n2 = TreeNode(2);
TreeNode n3 = TreeNode(3);

View File

@@ -91,8 +91,6 @@ func TestMyHeap(t *testing.T) {
}
func TestTopKHeap(t *testing.T) {
/* 初始化堆 */
// 初始化大顶堆
nums := []int{1, 7, 6, 3, 2}
k := 3
res := topKHeap(nums, k)

View File

@@ -51,7 +51,6 @@ func TestDeque(t *testing.T) {
func TestArrayDeque(t *testing.T) {
/* 初始化双向队列 */
// 在 Go 中,将 list 作为双向队列使用
deque := newArrayDeque(16)
/* 元素入队 */
@@ -102,7 +101,7 @@ func TestLinkedListDeque(t *testing.T) {
deque.pushLast(4)
deque.pushFirst(3)
deque.pushFirst(1)
fmt.Print("队列 deque = ")
fmt.Print("双向队列 deque = ")
PrintList(deque.toList())
// 访问队首元素

View File

@@ -84,7 +84,7 @@ func TestArrayQueue(t *testing.T) {
for i := 0; i < 10; i++ {
queue.push(i)
queue.pop()
fmt.Print("第", i, "轮入队 + 出队后 queue =")
fmt.Print("第 ", i, " 轮入队 + 出队后 queue =")
PrintSlice(queue.toSlice())
}
}

View File

@@ -11,7 +11,7 @@ import java.util.*;
public class list {
public static void main(String[] args) {
/* 初始化列表 */
// 注意数组的元素类型是 int[] 的包装类 Integer[]
// 注意数组类型需为 Integer[] 而非 int[],因为列表元素只能是 int 的包装类 Integer
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
System.out.println("列表 nums = " + nums);

View File

@@ -30,7 +30,7 @@ if __name__ == "__main__":
tup = (12836, "小哈")
hash_tup = hash(tup)
print(f"元组 {tup} 的哈希值为 {hash(hash_tup)}")
print(f"元组 {tup} 的哈希值为 {hash_tup}")
obj = ListNode(0)
hash_obj = hash(obj)

View File

@@ -24,9 +24,9 @@ if __FILE__ == $0
hash_str = str.hash
puts "字符串 #{str} 的哈希值为 #{hash_str}"
tup = [12836, '小哈']
hash_tup = tup.hash
puts "元组 #{tup} 的哈希值为 #{hash_tup}"
arr = [12836, '小哈']
hash_arr = arr.hash
puts "数组 #{arr} 的哈希值为 #{hash_arr}"
obj = ListNode.new(0)
hash_obj = obj.hash

View File

@@ -127,13 +127,13 @@ if __FILE__ == $0
deque.push_last(4)
puts "元素 4 队尾入队后 deque = #{deque.to_array}"
deque.push_first(1)
puts "元素 1 队尾入队后 deque = #{deque.to_array}"
puts "元素 1 队首入队后 deque = #{deque.to_array}"
# 元素出队
pop_last = deque.pop_last
puts "队尾出队元素 = #{pop_last},队尾出队后 deque = #{deque.to_array}"
pop_first = deque.pop_first
puts "队尾出队元素 = #{pop_first},队尾出队后 deque = #{deque.to_array}"
puts "队首出队元素 = #{pop_first},队首出队后 deque = #{deque.to_array}"
# 获取双向队列的长度
size = deque.size

View File

@@ -7,10 +7,10 @@ Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
### Driver Code ###
if __FILE__ == $0
# 初始化双向队列
# Ruby 没有内直的双端队列,只能把 Array 当作双端队列来使用
# Ruby 没有内置的双端队列,只能把 Array 当作双端队列来使用
deque = []
# 元素如队
# 元素入队
deque << 2
deque << 5
deque << 4
@@ -26,7 +26,7 @@ if __FILE__ == $0
puts "队尾元素 peek_last = #{peek_last}"
# 元素出队
# 请注意,由于是数组, Array#shift 方法的时间复杂度为 O(n)
# 请注意,由于是数组,Array#shift 方法的时间复杂度为 O(n)
pop_front = deque.shift
puts "队首出队元素 pop_front = #{pop_front},队首出队后 deque = #{deque}"
pop_back = deque.pop

View File

@@ -4,11 +4,11 @@ Created Time: 2024-04-06
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 双向链表节点
### 双向链表节点 ###
class ListNode
attr_accessor :val
attr_accessor :next # 后继节点引用
attr_accessor :prev # 前躯节点引用
attr_accessor :prev # 前驱节点引用
### 构造方法 ###
def initialize(val)
@@ -101,7 +101,7 @@ class LinkedListDeque
pop(true)
end
### 队首出队 ###
### 队尾出队 ###
def pop_last
pop(false)
end
@@ -145,7 +145,7 @@ if __FILE__ == $0
peek_first = deque.peek_first
puts "队首元素 peek_first = #{peek_first}"
peek_last = deque.peek_last
puts "队首元素 peek_last = #{peek_last}"
puts "队尾元素 peek_last = #{peek_last}"
# 元素入队
deque.push_last(4)

View File

@@ -74,7 +74,7 @@ if __FILE__ == $0
# 初始化队列
queue = LinkedListQueue.new
# 元素如队
# 元素入队
queue.push(1)
queue.push(3)
queue.push(2)

View File

@@ -7,7 +7,7 @@ Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
### Driver Code ###
if __FILE__ == $0
# 初始化队列
# Ruby 内置的队列(Thread::Queue) 没有 peek 和遍历方法,可以把 Array 当作队列来使用
# Ruby 内置的队列(Thread::Queue)没有 peek 和遍历方法,可以把 Array 当作队列来使用
queue = []
# 元素入队
@@ -23,7 +23,7 @@ if __FILE__ == $0
puts "队首元素 peek = #{peek}"
# 元素出队
# 清注意,由于是数组,Array#shift 方法时间复杂度为 O(n)
# 请注意,由于是数组,Array#shift 方法的时间复杂度为 O(n)
pop = queue.shift
puts "出队元素 pop = #{pop}"
puts "出队后 queue = #{queue}"

View File

@@ -45,5 +45,5 @@ fn main() {
let mut hasher = DefaultHasher::new();
node.borrow().val.hash(&mut hasher);
let hash = hasher.finish();
println!("节点对象 {:?} 的哈希值为{}", node, hash);
println!("节点对象 {:?} 的哈希值为 {}", node, hash);
}

View File

@@ -9,7 +9,7 @@ use hello_algo_rust::include::print_util;
/* Driver Code */
pub fn main() {
// 初始化栈
// 在 rust 中,推荐将 Vec 当作栈来使用
// 在 Rust 中,推荐将 Vec 当作栈来使用
let mut stack: Vec<i32> = Vec::new();
// 元素入栈

View File

@@ -9,10 +9,10 @@ nums: list[int] = [1, 3, 2, 5, 4]
/* 初始化数组 */
// 存储在栈上
int arr[5] = {};
int nums[5] = { 1, 3, 2, 5, 4 };
int nums[5] = {1, 3, 2, 5, 4};
// 存储在堆上(需要手动释放空间)
int* arr1 = new int[5] {};
int* nums1 = new int[5] { 1, 3, 2, 5, 4 };
int *arr1 = new int[5]{};
int *nums1 = new int[5]{1, 3, 2, 5, 4};
```
```java title="array.java"
@@ -22,7 +22,7 @@ int[] nums = { 1, 3, 2, 5, 4 };
```
```csharp title="array.cs"
/* 初始化数组 */
// 初始化数组
int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ]
int[] nums = [1, 3, 2, 5, 4];
```
@@ -32,38 +32,37 @@ int[] nums = [1, 3, 2, 5, 4];
var arr [5]int
// 在 Go 中,指定长度时([5]int)为数组,不指定长度时([]int)为切片
// 由于 Go 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度
// 为了方便实现扩容 extend() 方法,以下将切片(Slice)看作数组(Array)
// 为了方便实现扩容 extend() 函数,以下将切片(Slice)看作数组(Array)
nums := []int{1, 3, 2, 5, 4}
```
```swift title="array.swift"
/* 初始化数组 */
let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0]
let nums = [1, 3, 2, 5, 4]
var nums = [1, 3, 2, 5, 4]
```
```javascript title="array.js"
/* 初始化数组 */
var arr = new Array(5).fill(0);
var nums = [1, 3, 2, 5, 4];
const arr = new Array(5).fill(0);
let nums = [1, 3, 2, 5, 4];
```
```typescript title="array.ts"
/* 初始化数组 */
let arr: number[] = new Array(5).fill(0);
const arr: number[] = new Array(5).fill(0);
let nums: number[] = [1, 3, 2, 5, 4];
```
```dart title="array.dart"
/* 初始化数组 */
List<int> arr = List.filled(5, 0); // [0, 0, 0, 0, 0]
var arr = List.filled(5, 0); // [0, 0, 0, 0, 0]
List<int> nums = [1, 3, 2, 5, 4];
```
```rust title="array.rs"
/* 初始化数组 */
let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0]
let slice: &[i32] = &[0; 5];
// 在 Rust 中,指定长度时([i32; 5])为数组,不指定长度时(&[i32])为切片
// 由于 Rust 的数组被设计为在编译期确定长度,因此只能使用常量来指定长度
// Vector 是 Rust 一般情况下用作动态数组的类型
@@ -73,13 +72,13 @@ let nums: Vec<i32> = vec![1, 3, 2, 5, 4];
```c title="array.c"
/* 初始化数组 */
int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 }
int nums[5] = { 1, 3, 2, 5, 4 };
int arr[5] = {0}; // { 0, 0, 0, 0, 0 }
int nums[] = {1, 3, 2, 5, 4};
```
```kotlin title="array.kt"
/* 初始化数组 */
var arr = IntArray(5) // { 0, 0, 0, 0, 0 }
val arr = IntArray(5) // { 0, 0, 0, 0, 0 }
var nums = intArrayOf(1, 3, 2, 5, 4)
```

View File

@@ -2,48 +2,53 @@
```python title=""
class ListNode:
"""链表节点类"""
def __init__(self, val: int):
self.val: int = val # 节点值
self.next: ListNode | None = None # 指向下一节点的引用
self.val: int = val # 节点值
self.next: ListNode | None = None # 指向下一节点的引用
```
```cpp title=""
/* 链表节点结构体 */
/* 链表节点 */
struct ListNode {
int val; // 节点值
ListNode *next; // 指向下一节点的指针
ListNode(int x) : val(x), next(nullptr) {} // 构造函数
int val; // 节点值
ListNode *next; // 后继节点指针
ListNode(int x) : val(x), next(nullptr) {
}
};
```
```java title=""
/* 链表节点类 */
class ListNode {
int val; // 节点值
ListNode next; // 指向下一节点的引用
ListNode(int x) { val = x; } // 构造函数
/* 链表节点 */
public class ListNode {
public int val; // 节点值
public ListNode next; // 指向下一节点的引用
public ListNode(int x) {
val = x;
}
}
```
```csharp title=""
/* 链表节点类 */
class ListNode(int x) { //构造函数
public int val = x; // 节点值
public ListNode? next; // 指向下一节点的引用
/* 链表节点 */
public class ListNode(int x) {
public int val = x; // 节点值
public ListNode? next; // 指向下一节点的引用
}
```
```go title=""
/* 链表节点结构体 */
// ListNode 链表节点
type ListNode struct {
Val int // 节点值
Next *ListNode // 指向下一节点的指针
Next *ListNode // 后继节点指针
}
// NewListNode 构造函数,创建一个新的链表
func NewListNode(val int) *ListNode {
// NewListNode 链表节点构造函数
func NewListNode(v int) *ListNode {
return &ListNode{
Val: val,
Val: v,
Next: nil,
}
}
@@ -62,44 +67,54 @@ class ListNode {
```
```javascript title=""
/* 链表节点类 */
/* 链表节点 */
class ListNode {
val; // 节点值
next; // 指向下一节点的引用(指针)
constructor(val, next) {
this.val = (val === undefined ? 0 : val); // 节点值
this.next = (next === undefined ? null : next); // 指向下一节点的引用
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
```
```typescript title=""
/* 链表节点类 */
/* 链表节点 */
class ListNode {
val: number;
next: ListNode | null;
val: number; // 节点值
next: ListNode | null; // 指向下一节点的引用
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val; // 节点值
this.next = next === undefined ? null : next; // 指向下一节点的引用
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
```
```dart title=""
/* 链表节点类 */
/* 链表节点 */
class ListNode {
int val; // 节点值
ListNode? next; // 指向下一节点的引用
ListNode(this.val, [this.next]); // 构造函数
}
```
```rust title=""
use std::rc::Rc;
use std::cell::RefCell;
/* 链表节点类 */
use std::rc::Rc;
/* 链表节点 */
#[derive(Debug)]
struct ListNode {
val: i32, // 节点值
next: Option<Rc<RefCell<ListNode>>>, // 指向下一节点的指针
pub struct 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 }))
}
}
```
@@ -110,10 +125,10 @@ typedef struct ListNode {
struct ListNode *next; // 指向下一节点的指针
} ListNode;
/* 构造函数 */
/* 构造函数,初始化一个新节点 */
ListNode *newListNode(int val) {
ListNode *node;
node = (ListNode *) malloc(sizeof(ListNode));
node = (ListNode *)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
return node;
@@ -121,16 +136,14 @@ ListNode *newListNode(int val) {
```
```kotlin title=""
/* 链表节点类 */
// 构造方法
class ListNode(x: Int) {
val _val: Int = x // 节点值
var next: ListNode? = null // 指向下一个节点的引用
/* 链表节点 */
class ListNode(var _val: Int) {
var next: ListNode? = null // 指向下一节点的引用
}
```
```ruby title=""
# 链表节点类
### 链表节点类 ###
class ListNode
attr_accessor :val # 节点值
attr_accessor :next # 指向下一节点的引用
@@ -161,11 +174,11 @@ n3.next = n4
```cpp title="linked_list.cpp"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
ListNode* n0 = new ListNode(1);
ListNode* n1 = new ListNode(3);
ListNode* n2 = new ListNode(2);
ListNode* n3 = new ListNode(5);
ListNode* n4 = new ListNode(4);
ListNode *n0 = new ListNode(1);
ListNode *n1 = new ListNode(3);
ListNode *n2 = new ListNode(2);
ListNode *n3 = new ListNode(5);
ListNode *n4 = new ListNode(4);
// 构建节点之间的引用
n0->next = n1;
n1->next = n2;
@@ -189,7 +202,7 @@ n3.next = n4;
```
```csharp title="linked_list.cs"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化链表 1 -> 3 -> 2 -> 5 -> 4
// 初始化各个节点
ListNode n0 = new(1);
ListNode n1 = new(3);
@@ -211,6 +224,7 @@ n1 := NewListNode(3)
n2 := NewListNode(2)
n3 := NewListNode(5)
n4 := NewListNode(4)
// 构建节点之间的引用
n0.Next = n1
n1.Next = n2
@@ -264,7 +278,7 @@ n3.next = n4;
```
```dart title="linked_list.dart"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化链表 1 -> 3 -> 2 -> 5 -> 4
// 初始化各个节点
ListNode n0 = ListNode(1);
ListNode n1 = ListNode(3);
@@ -281,11 +295,11 @@ n3.next = n4;
```rust title="linked_list.rs"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None }));
let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None }));
let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None }));
let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None }));
let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None }));
let n0 = ListNode::new(1);
let n1 = ListNode::new(3);
let n2 = ListNode::new(2);
let n3 = ListNode::new(5);
let n4 = ListNode::new(4);
// 构建节点之间的引用
n0.borrow_mut().next = Some(n1.clone());
@@ -297,11 +311,11 @@ n3.borrow_mut().next = Some(n4.clone());
```c title="linked_list.c"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
ListNode* n0 = newListNode(1);
ListNode* n1 = newListNode(3);
ListNode* n2 = newListNode(2);
ListNode* n3 = newListNode(5);
ListNode* n4 = newListNode(4);
ListNode *n0 = newListNode(1);
ListNode *n1 = newListNode(3);
ListNode *n2 = newListNode(2);
ListNode *n3 = newListNode(5);
ListNode *n4 = newListNode(4);
// 构建节点之间的引用
n0->next = n1;
n1->next = n2;
@@ -317,11 +331,12 @@ val n1 = ListNode(3)
val n2 = ListNode(2)
val n3 = ListNode(5)
val n4 = ListNode(4)
// 构建节点之间的引用
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
```
```ruby title="linked_list.rb"
@@ -345,39 +360,46 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2
<!-- [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 # 指向前驱节点的引用
"""构造方法"""
self.val: int = val # 节点值
self.next: ListNode | None = None # 后继节点引用
self.prev: ListNode | None = None # 前驱节点引用
```
```cpp title=""
/* 双向链表节点结构体 */
struct ListNode {
int val; // 节点值
ListNode *next; // 指向后继节点的指针
ListNode *prev; // 指向前驱节点的指针
ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // 构造函数
/* 双向链表节点 */
struct DoublyListNode {
int val; // 节点值
DoublyListNode *next; // 后继节点指针
DoublyListNode *prev; // 前驱节点指针
DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) {
}
};
```
```java title=""
/* 双向链表节点类 */
/* 双向链表节点 */
class ListNode {
int val; // 节点值
ListNode next; // 指向后继节点的引用
ListNode prev; // 指向前驱节点的引用
ListNode(int x) { val = x; } // 构造函数
int val; // 节点值
ListNode next; // 后继节点引用
ListNode prev; // 前驱节点引用
ListNode(int val) {
this.val = val;
prev = next = null;
}
}
```
```csharp title=""
/* 双向链表节点类 */
class ListNode(int x) { // 构造函数
public int val = x; // 节点值
public ListNode? next; // 指向后继节点的引用
public ListNode? prev; // 指向前驱节点的引用
/* 双向链表节点 */
public class ListNode(int val) {
public int val = val; // 节点值
public ListNode? next = null; // 后继节点引用
public ListNode? prev = null; // 前驱节点引用
}
```
@@ -385,8 +407,8 @@ class ListNode(int x) { // 构造函数
/* 双向链表节点结构体 */
type DoublyListNode struct {
Val int // 节点值
Next *DoublyListNode // 指向后继节点的指针
Prev *DoublyListNode // 指向前驱节点的指针
Next *DoublyListNode // 后继节点指针
Prev *DoublyListNode // 前驱节点指针
}
// NewDoublyListNode 初始化
@@ -400,117 +422,119 @@ func NewDoublyListNode(val int) *DoublyListNode {
```
```swift title=""
/* 双向链表节点类 */
/* 双向链表节点 */
class ListNode {
var val: Int // 节点值
var next: ListNode? // 指向后继节点的引用
var prev: ListNode? // 指向前驱节点的引用
var next: ListNode? // 后继节点引用
weak var prev: ListNode? // 前驱节点引用
init(x: Int) { // 构造函数
val = x
init(val: Int) {
self.val = val
}
}
```
```javascript title=""
/* 双向链表节点类 */
/* 双向链表节点 */
class ListNode {
constructor(val, next, prev) {
this.val = val === undefined ? 0 : val; // 节点值
this.next = next === undefined ? null : next; // 指向后继节点的引用
this.prev = prev === undefined ? null : prev; // 指向前驱节点的引用
prev; // 前驱节点引用(指针)
next; // 后继节点引用(指针)
val; // 节点值
constructor(val) {
this.val = val;
this.next = null;
this.prev = null;
}
}
```
```typescript title=""
/* 双向链表节点类 */
/* 双向链表节点 */
class ListNode {
val: number;
next: ListNode | null;
prev: ListNode | null;
constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) {
this.val = val === undefined ? 0 : val; // 节点值
this.next = next === undefined ? null : next; // 指向后继节点的引用
this.prev = prev === undefined ? null : prev; // 指向前驱节点的引用
prev: ListNode | null; // 前驱节点引用(指针)
next: ListNode | null; // 后继节点引用(指针)
val: number; // 节点值
constructor(val: number) {
this.val = val;
this.next = null;
this.prev = null;
}
}
```
```dart title=""
/* 双向链表节点类 */
/* 双向链表节点 */
class ListNode {
int val; // 节点值
ListNode? next; // 指向后继节点的引用
ListNode? prev; // 指向前驱节点的引用
ListNode(this.val, [this.next, this.prev]); // 构造函数
int val; // 节点值
ListNode? next; // 后继节点引用
ListNode? prev; // 前驱节点引用
ListNode(this.val, {this.next, this.prev});
}
```
```rust title=""
use std::rc::Rc;
use std::cell::RefCell;
use std::rc::Rc;
/* 双向链表节点类型 */
#[derive(Debug)]
struct ListNode {
val: i32, // 节点值
next: Option<Rc<RefCell<ListNode>>>, // 指向后继节点的指针
prev: Option<Rc<RefCell<ListNode>>>, // 指向前驱节点的指针
/* 双向链表节点 */
pub struct ListNode<T> {
pub val: T, // 节点值
pub next: Option<Rc<RefCell<ListNode<T>>>>, // 后继节点指针
pub prev: Option<Rc<RefCell<ListNode<T>>>>, // 前驱节点指针
}
/* 构造函数 */
impl ListNode {
fn new(val: i32) -> Self {
ListNode {
impl<T> ListNode<T> {
pub fn new(val: T) -> Rc<RefCell<ListNode<T>>> {
Rc::new(RefCell::new(ListNode {
val,
next: None,
prev: None,
}
}))
}
}
```
```c title=""
/* 双向链表节点结构体 */
typedef struct ListNode {
int val; // 节点值
struct ListNode *next; // 指向后继节点的指针
struct ListNode *prev; // 指向前驱节点的指针
} ListNode;
/* 双向链表节点 */
typedef struct DoublyListNode {
int val; // 节点值
struct DoublyListNode *next; // 后继节点指针
struct DoublyListNode *prev; // 前驱节点指针
} DoublyListNode;
/* 构造函数 */
ListNode *newListNode(int val) {
ListNode *node;
node = (ListNode *) malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
node->prev = NULL;
return node;
DoublyListNode *newDoublyListNode(int num) {
DoublyListNode *new = (DoublyListNode *)malloc(sizeof(DoublyListNode));
new->val = num;
new->next = NULL;
new->prev = NULL;
return new;
}
```
```kotlin title=""
/* 双向链表节点类 */
// 构造方法
class ListNode(x: Int) {
val _val: Int = x // 节点值
var next: ListNode? = null // 指向后继节点的引用
var prev: ListNode? = null // 指向前驱节点的引用
/* 双向链表节点 */
class ListNode(
var _val: Int // 节点值
) {
var next: ListNode? = null // 后继节点引用
var prev: ListNode? = null // 前驱节点引用
}
```
```ruby title=""
# 双向链表节点类
### 双向链表节点 ###
class ListNode
attr_accessor :val # 节点值
attr_accessor :next # 指向后继节点的引用
attr_accessor :prev # 指向前驱节点的引用
attr_accessor :val # 节点值
attr_accessor :next # 后继节点引用
attr_accessor :prev # 前驱节点引用
def initialize(val=0, next_node=nil, prev_node=nil)
### 构造方法 ###
def initialize(val)
@val = val
@next = next_node
@prev = prev_node
end
end
```

View File

@@ -2,25 +2,24 @@
```python title="list.py"
# 初始化列表
# 无初始值
nums1: list[int] = []
empty_nums: list[int] = []
# 有初始值
nums: list[int] = [1, 3, 2, 5, 4]
```
```cpp title="list.cpp"
/* 初始化列表 */
// 需注意,C++ 中 vector 即是本文描述的 nums
// 无初始值
vector<int> nums1;
vector<int> emptyNums;
// 有初始值
vector<int> nums = { 1, 3, 2, 5, 4 };
vector<int> nums = {1, 3, 2, 5, 4};
```
```java title="list.java"
/* 初始化列表 */
// 无初始值
List<Integer> nums1 = new ArrayList<>();
// 有初始值(注意数组的元素类型需为 int[] 的包装类 Integer[])
List<Integer> emptyNums = new ArrayList<>();
// 有初始值(注意数组类型需为 Integer[] 而非 int[],因为列表元素只能是 int 的包装类 Integer)
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
```
@@ -28,7 +27,7 @@ List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
```csharp title="list.cs"
/* 初始化列表 */
// 无初始值
List<int> nums1 = [];
List<int> emptyNums = [];
// 有初始值
int[] numbers = [1, 3, 2, 5, 4];
List<int> nums = [.. numbers];
@@ -37,7 +36,7 @@ List<int> nums = [.. numbers];
```go title="list_test.go"
/* 初始化列表 */
// 无初始值
nums1 := []int{}
emptyNums := []int{}
// 有初始值
nums := []int{1, 3, 2, 5, 4}
```
@@ -45,7 +44,7 @@ nums := []int{1, 3, 2, 5, 4}
```swift title="list.swift"
/* 初始化列表 */
// 无初始值
let nums1: [Int] = []
let emptyNums: [Int] = []
// 有初始值
var nums = [1, 3, 2, 5, 4]
```
@@ -53,7 +52,7 @@ var nums = [1, 3, 2, 5, 4]
```javascript title="list.js"
/* 初始化列表 */
// 无初始值
const nums1 = [];
const emptyNums = [];
// 有初始值
const nums = [1, 3, 2, 5, 4];
```
@@ -61,7 +60,7 @@ const nums = [1, 3, 2, 5, 4];
```typescript title="list.ts"
/* 初始化列表 */
// 无初始值
const nums1: number[] = [];
const emptyNums: number[] = [];
// 有初始值
const nums: number[] = [1, 3, 2, 5, 4];
```
@@ -69,15 +68,15 @@ const nums: number[] = [1, 3, 2, 5, 4];
```dart title="list.dart"
/* 初始化列表 */
// 无初始值
List<int> nums1 = [];
List<int> emptyNums = [];
// 有初始值
List<int> nums = [1, 3, 2, 5, 4];
```
```rust title="list.rs"
/* 初始化列表 */
// 初始化列表
// 无初始值
let nums1: Vec<i32> = Vec::new();
let empty_nums: Vec<i32> = Vec::new();
// 有初始值
let mut nums: Vec<i32> = vec![1, 3, 2, 5, 4];
```
@@ -89,62 +88,61 @@ let mut nums: Vec<i32> = vec![1, 3, 2, 5, 4];
```kotlin title="list.kt"
/* 初始化列表 */
// 无初始值
var nums1 = listOf<Int>()
val emptyNums = mutableListOf<Int>()
// 有初始值
var numbers = arrayOf(1, 3, 2, 5, 4)
var nums = numbers.toMutableList()
val nums = mutableListOf(1, 3, 2, 5, 4)
```
```ruby title="list.rb"
# 初始化列表
# 无初始值
nums1 = []
empty_nums = []
# 有初始值
nums = [1, 3, 2, 5, 4]
```
<!-- [tutor]{init_list_tutor} -->
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20%23%20%E6%97%A0%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20%23%20%E6%97%A0%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20empty_nums%20%3D%20%5B%5D%0A%20%20%20%20%23%20%E6%9C%89%E5%88%9D%E5%A7%8B%E5%80%BC%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
<!-- [snippet]{access_element} -->
```python title="list.py"
# 访问元素
num: int = nums[1] # 访问索引 1 处的元素
x: int = nums[1] # 访问索引 1 处的元素
# 更新元素
nums[1] = 0 # 将索引 1 处的元素更新为 0
nums[1] = 0 # 将索引 1 处的元素更新为 0
```
```cpp title="list.cpp"
/* 访问元素 */
int num = nums[1]; // 访问索引 1 处的元素
int num = nums[1]; // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
nums[1] = 0; // 将索引 1 处的元素更新为 0
```
```java title="list.java"
/* 访问元素 */
int num = nums.get(1); // 访问索引 1 处的元素
int num = nums.get(1); // 访问索引 1 处的元素
/* 更新元素 */
nums.set(1, 0); // 将索引 1 处的元素更新为 0
nums.set(1, 0); // 将索引 1 处的元素更新为 0
```
```csharp title="list.cs"
/* 访问元素 */
int num = nums[1]; // 访问索引 1 处的元素
int num = nums[1]; // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
nums[1] = 0; // 将索引 1 处的元素更新为 0
```
```go title="list_test.go"
/* 访问元素 */
num := nums[1] // 访问索引 1 处的元素
num := nums[1] // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0 // 将索引 1 处的元素更新为 0
nums[1] = 0 // 将索引 1 处的元素更新为 0
```
```swift title="list.swift"
@@ -157,33 +155,34 @@ nums[1] = 0 // 将索引 1 处的元素更新为 0
```javascript title="list.js"
/* 访问元素 */
const num = nums[1]; // 访问索引 1 处的元素
const num = nums[1]; // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
nums[1] = 0; // 将索引 1 处的元素更新为 0
```
```typescript title="list.ts"
/* 访问元素 */
const num: number = nums[1]; // 访问索引 1 处的元素
const num: number = nums[1]; // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
nums[1] = 0; // 将索引 1 处的元素更新为 0
```
```dart title="list.dart"
/* 访问元素 */
int num = nums[1]; // 访问索引 1 处的元素
int _num = nums[1]; // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
nums[1] = 0; // 将索引 1 处的元素更新为 0
```
```rust title="list.rs"
/* 访问元素 */
let num: i32 = nums[1]; // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
// 访问元素
let num = nums[1]; // 访问索引 1 处的元素
// 更新元素
nums[1] = 0; // 将索引 1 处的元素更新为 0
```
```c title="list.c"
@@ -192,20 +191,22 @@ nums[1] = 0; // 将索引 1 处的元素更新为 0
```kotlin title="list.kt"
/* 访问元素 */
val num = nums[1] // 访问索引 1 处的元素
val num = nums[1] // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0 // 将索引 1 处的元素更新为 0
nums[1] = 0 // 将索引 1 处的元素更新为 0
```
```ruby title="list.rb"
# 访问元素
num = nums[1] # 访问索引 1 处的元素
# 更新元素
nums[1] = 0 # 将索引 1 处的元素更新为 0
```
<!-- [tutor]{access_element_tutor} -->
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20%E8%AE%BF%E9%97%AE%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%86%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E4%B8%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%88%97%E8%A1%A8%0A%20%20%20%20nums%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%0A%20%20%20%20%23%20%E8%AE%BF%E9%97%AE%E5%85%83%E7%B4%A0%0A%20%20%20%20x%20%3D%20nums%5B1%5D%20%20%23%20%E8%AE%BF%E9%97%AE%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%0A%0A%20%20%20%20%23%20%E6%9B%B4%E6%96%B0%E5%85%83%E7%B4%A0%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20%E5%B0%86%E7%B4%A2%E5%BC%95%201%20%E5%A4%84%E7%9A%84%E5%85%83%E7%B4%A0%E6%9B%B4%E6%96%B0%E4%B8%BA%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
<!-- [snippet]{insert_remove_element} -->
```python title="list.py"
@@ -223,7 +224,7 @@ nums.append(4)
nums.insert(3, 6) # 在索引 3 处插入数字 6
# 删除元素
nums.pop(3) # 删除索引 3 处的元素
nums.pop(3) # 删除索引 3 处的元素
```
```cpp title="list.cpp"
@@ -238,10 +239,10 @@ nums.push_back(5);
nums.push_back(4);
/* 在中间插入元素 */
nums.insert(nums.begin() + 3, 6); // 在索引 3 处插入数字 6
nums.insert(nums.begin() + 3, 6); // 在索引 3 处插入数字 6
/* 删除元素 */
nums.erase(nums.begin() + 3); // 删除索引 3 处的元素
nums.erase(nums.begin() + 3); // 删除索引 3 处的元素
```
```java title="list.java"
@@ -256,10 +257,10 @@ nums.add(5);
nums.add(4);
/* 在中间插入元素 */
nums.add(3, 6); // 在索引 3 处插入数字 6
nums.add(3, 6); // 在索引 3 处插入数字 6
/* 删除元素 */
nums.remove(3); // 删除索引 3 处的元素
nums.remove(3); // 删除索引 3 处的元素
```
```csharp title="list.cs"
@@ -274,10 +275,10 @@ nums.Add(5);
nums.Add(4);
/* 在中间插入元素 */
nums.Insert(3, 6); // 在索引 3 处插入数字 6
nums.Insert(3, 6); // 在索引 3 处插入数字 6
/* 删除元素 */
nums.RemoveAt(3); // 删除索引 3 处的元素
nums.RemoveAt(3); // 删除索引 3 处的元素
```
```go title="list_test.go"
@@ -331,7 +332,7 @@ nums.push(4);
nums.splice(3, 0, 6); // 在索引 3 处插入数字 6
/* 删除元素 */
nums.splice(3, 1); // 删除索引 3 处的元素
nums.splice(3, 1); // 删除索引 3 处的元素
```
```typescript title="list.ts"
@@ -349,7 +350,7 @@ nums.push(4);
nums.splice(3, 0, 6); // 在索引 3 处插入数字 6
/* 删除元素 */
nums.splice(3, 1); // 删除索引 3 处的元素
nums.splice(3, 1); // 删除索引 3 处的元素
```
```dart title="list.dart"
@@ -371,21 +372,21 @@ nums.removeAt(3); // 删除索引 3 处的元素
```
```rust title="list.rs"
/* 清空列表 */
// 清空列表
nums.clear();
/* 在尾部添加元素 */
// 在尾部添加元素
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
/* 在中间插入元素 */
nums.insert(3, 6); // 在索引 3 处插入数字 6
// 在中间插入元素
nums.insert(3, 6); // 在索引 3 处插入数字 6
/* 删除元素 */
nums.remove(3); // 删除索引 3 处的元素
// 删除元素
nums.remove(3); // 删除索引 3 处的元素
```
```c title="list.c"
@@ -394,20 +395,20 @@ nums.remove(3); // 删除索引 3 处的元素
```kotlin title="list.kt"
/* 清空列表 */
nums.clear();
nums.clear()
/* 在尾部添加元素 */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
nums.add(1)
nums.add(3)
nums.add(2)
nums.add(5)
nums.add(4)
/* 在中间插入元素 */
nums.add(3, 6); // 在索引 3 处插入数字 6
nums.add(3, 6) // 在索引 3 处插入数字 6
/* 删除元素 */
nums.removeAt(3); // 删除索引 3 处的元素
nums.removeAt(3) // 删除索引 3 处的元素
```
```ruby title="list.rb"
@@ -452,8 +453,8 @@ for (int i = 0; i < nums.size(); i++) {
/* 直接遍历列表元素 */
count = 0;
for (int num : nums) {
count += num;
for (int x : nums) {
count += x;
}
```
@@ -465,8 +466,8 @@ for (int i = 0; i < nums.size(); i++) {
}
/* 直接遍历列表元素 */
for (int num : nums) {
count += num;
for (int x : nums) {
count += x;
}
```
@@ -479,8 +480,8 @@ for (int i = 0; i < nums.Count; i++) {
/* 直接遍历列表元素 */
count = 0;
foreach (int num in nums) {
count += num;
foreach (int x in nums) {
count += x;
}
```
@@ -493,8 +494,8 @@ for i := 0; i < len(nums); i++ {
/* 直接遍历列表元素 */
count = 0
for _, num := range nums {
count += num
for _, x := range nums {
count += x
}
```
@@ -507,8 +508,8 @@ for i in nums.indices {
/* 直接遍历列表元素 */
count = 0
for num in nums {
count += num
for x in nums {
count += x
}
```
@@ -521,8 +522,8 @@ for (let i = 0; i < nums.length; i++) {
/* 直接遍历列表元素 */
count = 0;
for (const num of nums) {
count += num;
for (const x of nums) {
count += x;
}
```
@@ -535,8 +536,8 @@ for (let i = 0; i < nums.length; i++) {
/* 直接遍历列表元素 */
count = 0;
for (const num of nums) {
count += num;
for (const x of nums) {
count += x;
}
```
@@ -544,13 +545,13 @@ for (const num of nums) {
/* 通过索引遍历列表 */
int count = 0;
for (var i = 0; i < nums.length; i++) {
count += nums[i];
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
for (var num in nums) {
count += num;
for (var x in nums) {
count += x;
}
```
@@ -563,8 +564,8 @@ for i in 0..nums.len() {
// 直接遍历列表元素
_count = 0;
for num in &nums {
_count += num;
for x in &nums {
_count += x;
}
```
@@ -580,8 +581,8 @@ for (i in nums.indices) {
}
/* 直接遍历列表元素 */
for (num in nums) {
count += num
for (j in nums) {
count += j
}
```
@@ -589,13 +590,13 @@ for (num in nums) {
# 通过索引遍历列表
count = 0
for i in 0...nums.length
count += nums[i]
count += nums[i]
end
# 直接遍历列表元素
count = 0
for num in nums
count += num
nums.each do |x|
count += x
end
```
@@ -605,13 +606,13 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{concat_list} -->
```python title="list.py"
# 拼接两个列表
nums1: list[int] = [6, 8, 7, 10, 9]
nums1 = [6, 8, 7, 10, 9]
nums += nums1 # 将列表 nums1 拼接到 nums 之后
```
```cpp title="list.cpp"
/* 拼接两个列表 */
vector<int> nums1 = { 6, 8, 7, 10, 9 };
vector<int> nums1 = {6, 8, 7, 10, 9};
// 将列表 nums1 拼接到 nums 之后
nums.insert(nums.end(), nums1.begin(), nums1.end());
```
@@ -619,19 +620,19 @@ nums.insert(nums.end(), nums1.begin(), nums1.end());
```java title="list.java"
/* 拼接两个列表 */
List<Integer> nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 }));
nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后
nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后
```
```csharp title="list.cs"
/* 拼接两个列表 */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后
nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后
```
```go title="list_test.go"
/* 拼接两个列表 */
nums1 := []int{6, 8, 7, 10, 9}
nums = append(nums, nums1...) // 将列表 nums1 拼接到 nums 之后
nums = append(nums, nums1...) // 将列表 nums1 拼接到 nums 之后
```
```swift title="list.swift"
@@ -643,25 +644,25 @@ nums.append(contentsOf: nums1) // 将列表 nums1 拼接到 nums 之后
```javascript title="list.js"
/* 拼接两个列表 */
const nums1 = [6, 8, 7, 10, 9];
nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后
nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后
```
```typescript title="list.ts"
/* 拼接两个列表 */
const nums1: number[] = [6, 8, 7, 10, 9];
nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后
nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后
```
```dart title="list.dart"
/* 拼接两个列表 */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后
nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后
```
```rust title="list.rs"
/* 拼接两个列表 */
let nums1: Vec<i32> = vec![6, 8, 7, 10, 9];
nums.extend(nums1);
// 拼接两个列表
let mut nums1 = vec![6, 8, 7, 10, 9];
nums.append(&mut nums1); // append 会移走 nums1 的元素,之后 nums1 为空
```
```c title="list.c"
@@ -670,8 +671,8 @@ nums.extend(nums1);
```kotlin title="list.kt"
/* 拼接两个列表 */
val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList()
nums.addAll(nums1) // 将列表 nums1 拼接到 nums 之后
val nums1 = mutableListOf(6, 8, 7, 10, 9)
nums.addAll(nums1) // 将列表 nums1 拼接到 nums 之后
```
```ruby title="list.rb"
@@ -691,12 +692,12 @@ nums.sort() # 排序后,列表元素从小到大排列
```cpp title="list.cpp"
/* 排序列表 */
sort(nums.begin(), nums.end()); // 排序后,列表元素从小到大排列
sort(nums.begin(), nums.end()); // 排序后,列表元素从小到大排列
```
```java title="list.java"
/* 排序列表 */
Collections.sort(nums); // 排序后,列表元素从小到大排列
Collections.sort(nums); // 排序后,列表元素从小到大排列
```
```csharp title="list.cs"
@@ -706,7 +707,7 @@ nums.Sort(); // 排序后,列表元素从小到大排列
```go title="list_test.go"
/* 排序列表 */
sort.Ints(nums) // 排序后,列表元素从小到大排列
sort.Ints(nums) // 排序后,列表元素从小到大排列
```
```swift title="list.swift"
@@ -716,12 +717,12 @@ nums.sort() // 排序后,列表元素从小到大排列
```javascript title="list.js"
/* 排序列表 */
nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列
nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列
```
```typescript title="list.ts"
/* 排序列表 */
nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列
nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列
```
```dart title="list.dart"
@@ -730,7 +731,7 @@ nums.sort(); // 排序后,列表元素从小到大排列
```
```rust title="list.rs"
/* 排序列表 */
// 排序列表
nums.sort(); // 排序后,列表元素从小到大排列
```

View File

@@ -2,44 +2,54 @@
```python title="built_in_hash.py"
num = 3
hash_num = hash(num)
print(f"整数 {num} 的哈希值为 {hash_num}")
# 整数 3 的哈希值为 3
bol = True
hash_bol = hash(bol)
print(f"布尔量 {bol} 的哈希值为 {hash_bol}")
# 布尔量 True 的哈希值为 1
dec = 3.14159
hash_dec = hash(dec)
print(f"小数 {dec} 的哈希值为 {hash_dec}")
# 小数 3.14159 的哈希值为 326484311674566659
str = "Hello 算法"
hash_str = hash(str)
print(f"字符串“{str}”的哈希值为 {hash_str}")
# 字符串“Hello 算法”的哈希值为 4617003410720528961
tup = (12836, "小哈")
hash_tup = hash(tup)
print(f"元组 {tup} 的哈希值为 {hash_tup}")
# 元组 (12836, '小哈') 的哈希值为 1029005403108185979
obj = ListNode(0)
hash_obj = hash(obj)
# 节点对象 <ListNode object at 0x1058fd810> 的哈希值为 274267521
print(f"节点对象 {obj} 的哈希值为 {hash_obj}")
# 节点对象 <modules.list_node.ListNode object at 0x1058fd810> 的哈希值为 274267521
```
```cpp title="built_in_hash.cpp"
int num = 3;
size_t hashNum = hash<int>()(num);
cout << "整数 " << num << " 的哈希值为 " << hashNum << "\n";
// 整数 3 的哈希值为 3
bool bol = true;
size_t hashBol = hash<bool>()(bol);
cout << "布尔量 " << bol << " 的哈希值为 " << hashBol << "\n";
// 布尔量 1 的哈希值为 1
double dec = 3.14159;
size_t hashDec = hash<double>()(dec);
cout << "小数 " << dec << " 的哈希值为 " << hashDec << "\n";
// 小数 3.14159 的哈希值为 4614256650576692846
string str = "Hello 算法";
size_t hashStr = hash<string>()(str);
cout << "字符串“" << str << "”的哈希值为 " << hashStr << "\n";
// 字符串“Hello 算法”的哈希值为 15466937326284535026
// 在 C++ 中,内置 std::hash() 仅提供基本数据类型的哈希值计算
@@ -49,53 +59,65 @@ size_t hashStr = hash<string>()(str);
```java title="built_in_hash.java"
int num = 3;
int hashNum = Integer.hashCode(num);
System.out.println("整数 " + num + " 的哈希值为 " + hashNum);
// 整数 3 的哈希值为 3
boolean bol = true;
int hashBol = Boolean.hashCode(bol);
System.out.println("布尔量 " + bol + " 的哈希值为 " + hashBol);
// 布尔量 true 的哈希值为 1231
double dec = 3.14159;
int hashDec = Double.hashCode(dec);
System.out.println("小数 " + dec + " 的哈希值为 " + hashDec);
// 小数 3.14159 的哈希值为 -1340954729
String str = "Hello 算法";
int hashStr = str.hashCode();
System.out.println("字符串“" + str + "”的哈希值为 " + hashStr);
// 字符串“Hello 算法”的哈希值为 -727081396
Object[] arr = { 12836, "小哈" };
int hashTup = Arrays.hashCode(arr);
int hashArr = Arrays.hashCode(arr);
System.out.println("数组 " + Arrays.toString(arr) + " 的哈希值为 " + hashArr);
// 数组 [12836, 小哈] 的哈希值为 1151158
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode();
System.out.println("节点对象 " + obj + " 的哈希值为 " + hashObj);
// 节点对象 utils.ListNode@7dc5e7b4 的哈希值为 2110121908
```
```csharp title="built_in_hash.cs"
int num = 3;
int hashNum = num.GetHashCode();
// 整数 3 的哈希值为 3;
Console.WriteLine("整数 " + num + " 的哈希值为 " + hashNum);
// 整数 3 的哈希值为 3
bool bol = true;
int hashBol = bol.GetHashCode();
// 布尔量 true 的哈希值为 1;
Console.WriteLine("布尔量 " + bol + " 的哈希值为 " + hashBol);
// 布尔量 True 的哈希值为 1
double dec = 3.14159;
int hashDec = dec.GetHashCode();
// 小数 3.14159 的哈希值为 -1340954729;
Console.WriteLine("小数 " + dec + " 的哈希值为 " + hashDec);
// 小数 3.14159 的哈希值为 -1340954729
string str = "Hello 算法";
int hashStr = str.GetHashCode();
// 字符串“Hello 算法”的哈希值为 -586107568;
Console.WriteLine("字符串“" + str + "”的哈希值为 " + hashStr);
// 字符串“Hello 算法”的哈希值为 -586107568
object[] arr = [12836, "小哈"];
int hashTup = arr.GetHashCode();
// 数组 [12836, 小哈] 的哈希值为 42931033;
int hashArr = arr.GetHashCode();
Console.WriteLine("数组 [" + string.Join(", ", arr) + "] 的哈希值为 " + hashArr);
// 数组 [12836, 小哈] 的哈希值为 42931033
ListNode obj = new(0);
int hashObj = obj.GetHashCode();
// 节点对象 0 的哈希值为 39053774;
Console.WriteLine("节点对象 " + obj + " 的哈希值为 " + hashObj);
// 节点对象 0 的哈希值为 39053774
```
```go title="built_in_hash.go"
@@ -105,26 +127,32 @@ int hashObj = obj.GetHashCode();
```swift title="built_in_hash.swift"
let num = 3
let hashNum = num.hashValue
print("整数 \(num) 的哈希值为 \(hashNum)")
// 整数 3 的哈希值为 9047044699613009734
let bol = true
let hashBol = bol.hashValue
print("布尔量 \(bol) 的哈希值为 \(hashBol)")
// 布尔量 true 的哈希值为 -4431640247352757451
let dec = 3.14159
let hashDec = dec.hashValue
print("小数 \(dec) 的哈希值为 \(hashDec)")
// 小数 3.14159 的哈希值为 -2465384235396674631
let str = "Hello 算法"
let hashStr = str.hashValue
print("字符串“\(str)”的哈希值为 \(hashStr)")
// 字符串“Hello 算法”的哈希值为 -7850626797806988787
let arr = [AnyHashable(12836), AnyHashable("小哈")]
let hashTup = arr.hashValue
let hashArr = arr.hashValue
print("数组 \(arr) 的哈希值为 \(hashArr)")
// 数组 [AnyHashable(12836), AnyHashable("小哈")] 的哈希值为 -2308633508154532996
let obj = ListNode(x: 0)
let hashObj = obj.hashValue
print("节点对象 \(obj) 的哈希值为 \(hashObj)")
// 节点对象 utils.ListNode 的哈希值为 -2434780518035996159
```
@@ -139,26 +167,32 @@ let hashObj = obj.hashValue
```dart title="built_in_hash.dart"
int num = 3;
int hashNum = num.hashCode;
print("整数 $num 的哈希值为 $hashNum");
// 整数 3 的哈希值为 34803
bool bol = true;
int hashBol = bol.hashCode;
// 布尔值 true 的哈希值为 1231
print("布尔量 $bol 的哈希值为 $hashBol");
// 布尔量 true 的哈希值为 1231
double dec = 3.14159;
int hashDec = dec.hashCode;
print("小数 $dec 的哈希值为 $hashDec");
// 小数 3.14159 的哈希值为 2570631074981783
String str = "Hello 算法";
int hashStr = str.hashCode;
print("字符串“$str”的哈希值为 $hashStr");
// 字符串“Hello 算法”的哈希值为 468167534
List arr = [12836, "小哈"];
int hashArr = arr.hashCode;
print("数组 $arr 的哈希值为 $hashArr");
// 数组 [12836, 小哈] 的哈希值为 976512528
ListNode obj = new ListNode(0);
ListNode obj = ListNode(0);
int hashObj = obj.hashCode;
print("节点对象 $obj 的哈希值为 $hashObj");
// 节点对象 Instance of 'ListNode' 的哈希值为 1033450432
```
@@ -170,37 +204,43 @@ let num = 3;
let mut num_hasher = DefaultHasher::new();
num.hash(&mut num_hasher);
let hash_num = num_hasher.finish();
println!("整数 {} 的哈希值为 {}", num, hash_num);
// 整数 3 的哈希值为 568126464209439262
let bol = true;
let mut bol_hasher = DefaultHasher::new();
bol.hash(&mut bol_hasher);
let hash_bol = bol_hasher.finish();
println!("布尔量 {} 的哈希值为 {}", bol, hash_bol);
// 布尔量 true 的哈希值为 4952851536318644461
let dec: f32 = 3.14159;
let mut dec_hasher = DefaultHasher::new();
dec.to_bits().hash(&mut dec_hasher);
let hash_dec = dec_hasher.finish();
println!("小数 {} 的哈希值为 {}", dec, hash_dec);
// 小数 3.14159 的哈希值为 2566941990314602357
let str = "Hello 算法";
let mut str_hasher = DefaultHasher::new();
str.hash(&mut str_hasher);
let hash_str = str_hasher.finish();
println!("字符串“{}”的哈希值为 {}", str, hash_str);
// 字符串“Hello 算法”的哈希值为 16092673739211250988
let arr = (&12836, &"小哈");
let tup = (&12836, &"小哈");
let mut tup_hasher = DefaultHasher::new();
arr.hash(&mut tup_hasher);
tup.hash(&mut tup_hasher);
let hash_tup = tup_hasher.finish();
println!("元组 {:?} 的哈希值为 {}", tup, hash_tup);
// 元组 (12836, "小哈") 的哈希值为 1885128010422702749
let node = ListNode::new(42);
let mut hasher = DefaultHasher::new();
node.borrow().val.hash(&mut hasher);
let hash = hasher.finish();
// 节点对象 RefCell { value: ListNode { val: 42, next: None } } 的哈希值为15387811073369036852
let mut node_hasher = DefaultHasher::new();
node.borrow().val.hash(&mut node_hasher);
let hash_node = node_hasher.finish();
println!("节点对象 {:?} 的哈希值为 {}", node, hash_node);
// 节点对象 RefCell { value: ListNode { val: 42, next: None } } 的哈希值为 15387811073369036852
```
```c title="built_in_hash.c"
@@ -210,54 +250,66 @@ let hash = hasher.finish();
```kotlin title="built_in_hash.kt"
val num = 3
val hashNum = num.hashCode()
println("整数 $num 的哈希值为 $hashNum")
// 整数 3 的哈希值为 3
val bol = true
val hashBol = bol.hashCode()
println("布尔量 $bol 的哈希值为 $hashBol")
// 布尔量 true 的哈希值为 1231
val dec = 3.14159
val hashDec = dec.hashCode()
println("小数 $dec 的哈希值为 $hashDec")
// 小数 3.14159 的哈希值为 -1340954729
val str = "Hello 算法"
val hashStr = str.hashCode()
println("字符串“$str”的哈希值为 $hashStr")
// 字符串“Hello 算法”的哈希值为 -727081396
val arr = arrayOf<Any>(12836, "小哈")
val hashTup = arr.hashCode()
// 数组 [12836, 小哈] 的哈希值为 189568618
val hashArr = arr.contentHashCode()
println("数组 ${arr.contentToString()} 的哈希值为 $hashArr")
// 数组 [12836, 小哈] 的哈希值为 1151158
val obj = ListNode(0)
val hashObj = obj.hashCode()
println("节点对象 $obj 的哈希值为 $hashObj")
// 节点对象 utils.ListNode@1d81eb93 的哈希值为 495053715
```
```ruby title="built_in_hash.rb"
num = 3
hash_num = num.hash
puts "整数 #{num} 的哈希值为 #{hash_num}"
# 整数 3 的哈希值为 -4385856518450339636
bol = true
hash_bol = bol.hash
puts "布尔量 #{bol} 的哈希值为 #{hash_bol}"
# 布尔量 true 的哈希值为 -1617938112149317027
dec = 3.14159
hash_dec = dec.hash
puts "小数 #{dec} 的哈希值为 #{hash_dec}"
# 小数 3.14159 的哈希值为 -1479186995943067893
str = "Hello 算法"
hash_str = str.hash
puts "字符串“#{str}”的哈希值为 #{hash_str}"
# 字符串“Hello 算法”的哈希值为 -4075943250025831763
tup = [12836, '小哈']
hash_tup = tup.hash
# 元组 (12836, '小哈') 的哈希值为 1999544809202288822
arr = [12836, '小哈']
hash_arr = arr.hash
puts "数组 #{arr} 的哈希值为 #{hash_arr}"
# 数组 [12836, "小哈"] 的哈希值为 1999544809202288822
obj = ListNode.new(0)
hash_obj = obj.hash
puts "节点对象 #{obj} 的哈希值为 #{hash_obj}"
# 节点对象 #<ListNode:0x000078133140ab70> 的哈希值为 4302940560806366381
```
<!-- [tutor]{builtin_hash_tutor} -->
https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20%E5%B8%83%E5%B0%94%E9%87%8F%20True%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20%E5%AD%97%E7%AC%A6%E4%B8%B2%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836,%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20%E5%85%83%E7%BB%84%20%2812836,%20'%E5%B0%8F%E5%93%88'%29%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%AF%B9%E8%B1%A1%20%3CListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%90%8E%E7%BB%A7%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20print%28f%22%E6%95%B4%E6%95%B0%20%7Bnum%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_num%7D%22%29%0A%20%20%20%20%23%20%E6%95%B4%E6%95%B0%203%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20print%28f%22%E5%B8%83%E5%B0%94%E9%87%8F%20%7Bbol%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_bol%7D%22%29%0A%20%20%20%20%23%20%E5%B8%83%E5%B0%94%E9%87%8F%20True%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20print%28f%22%E5%B0%8F%E6%95%B0%20%7Bdec%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_dec%7D%22%29%0A%20%20%20%20%23%20%E5%B0%8F%E6%95%B0%203.14159%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20print%28f%22%E5%AD%97%E7%AC%A6%E4%B8%B2%E2%80%9C%7Bstr%7D%E2%80%9D%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_str%7D%22%29%0A%20%20%20%20%23%20%E5%AD%97%E7%AC%A6%E4%B8%B2%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836,%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20print%28f%22%E5%85%83%E7%BB%84%20%7Btup%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_tup%7D%22%29%0A%20%20%20%20%23%20%E5%85%83%E7%BB%84%20%2812836,%20%27%E5%B0%8F%E5%93%88%27%29%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20print%28f%22%E8%8A%82%E7%82%B9%E5%AF%B9%E8%B1%A1%20%7Bobj%7D%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20%7Bhash_obj%7D%22%29%0A%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%AF%B9%E8%B1%A1%20%3Cmodules.list_node.ListNode%20object%20at%200x1058fd810%3E%20%E7%9A%84%E5%93%88%E5%B8%8C%E5%80%BC%E4%B8%BA%20274267521%0A&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false

View File

@@ -1,7 +1,7 @@
<!-- [snippet]{hash_map_operations} -->
```python title="hash_map.py"
# 初始化哈希表
hmap: dict = {}
hmap = dict[int, str]()
# 添加操作
# 在哈希表中添加键值对 (key, value)
@@ -128,6 +128,7 @@ map.removeValue(forKey: 10583)
```javascript title="hash_map.js"
/* 初始化哈希表 */
const map = new Map();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
map.set(12836, '小哈');
@@ -148,6 +149,7 @@ map.delete(10583);
```typescript title="hash_map.ts"
/* 初始化哈希表 */
const map = new Map<number, string>();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
map.set(12836, '小哈');
@@ -155,24 +157,19 @@ map.set(15937, '小啰');
map.set(16750, '小算');
map.set(13276, '小法');
map.set(10583, '小鸭');
console.info('\n添加完成后,哈希表为\nKey -> Value');
console.info(map);
/* 查询操作 */
// 向哈希表中输入键 key ,得到值 value
let name = map.get(15937);
console.info('\n输入学号 15937 ,查询到姓名 ' + name);
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
map.delete(10583);
console.info('\n删除 10583 后,哈希表为\nKey -> Value');
console.info(map);
```
```dart title="hash_map.dart"
/* 初始化哈希表 */
Map<int, String> map = {};
final Map<int, String> map = {};
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
@@ -184,7 +181,7 @@ map[10583] = "小鸭";
/* 查询操作 */
// 向哈希表中输入键 key ,得到值 value
String? name = map[15937];
final String? name = map[15937];
/* 删除操作 */
// 在哈希表中删除键值对 (key, value)
@@ -194,24 +191,24 @@ map.remove(10583);
```rust title="hash_map.rs"
use std::collections::HashMap;
/* 初始化哈希表 */
let mut map: HashMap<i32, String> = HashMap::new();
// 初始化哈希表
let mut map = HashMap::new();
/* 添加操作 */
// 添加操作
// 在哈希表中添加键值对 (key, value)
map.insert(12836, "小哈".to_string());
map.insert(15937, "小啰".to_string());
map.insert(16750, "小算".to_string());
map.insert(13276, "小法".to_string());
map.insert(10583, "小鸭".to_string());
map.insert(12836, "小哈");
map.insert(15937, "小啰");
map.insert(16750, "小算");
map.insert(13276, "小法");
map.insert(10583, "小鸭");
/* 查询操作 */
// 查询操作
// 向哈希表中输入键 key ,得到值 value
let _name: Option<&String> = map.get(&15937);
let name = map.get(&15937).copied().unwrap();
/* 删除操作 */
// 删除操作
// 在哈希表中删除键值对 (key, value)
let _removed_value: Option<String> = map.remove(&10583);
_ = map.remove(&10583);
```
```c title="hash_map.c"
@@ -220,7 +217,7 @@ let _removed_value: Option<String> = map.remove(&10583);
```kotlin title="hash_map.kt"
/* 初始化哈希表 */
val map = HashMap<Int,String>()
val map = HashMap<Int, String>()
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
@@ -269,52 +266,59 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
# 遍历键值对 key->value
for key, value in hmap.items():
print(key, "->", value)
# 单独遍历键 key
for key in hmap.keys():
print(key)
# 单独遍历值 value
for value in hmap.values():
print(value)
for val in hmap.values():
print(val)
```
```cpp title="hash_map.cpp"
/* 遍历哈希表 */
// 遍历键值对 key->value
for (auto kv: map) {
for (auto kv : map) {
cout << kv.first << " -> " << kv.second << endl;
}
// 使用迭代器遍历 key->value
for (auto iter = map.begin(); iter != map.end(); iter++) {
cout << iter->first << "->" << iter->second << endl;
cout << iter->first << " -> " << iter->second << endl;
}
```
```java title="hash_map.java"
/* 遍历哈希表 */
// 遍历键值对 key->value
for (Map.Entry <Integer, String> kv: map.entrySet()) {
for (Map.Entry<Integer, String> kv : map.entrySet()) {
System.out.println(kv.getKey() + " -> " + kv.getValue());
}
// 单独遍历键 key
for (int key: map.keySet()) {
for (int key : map.keySet()) {
System.out.println(key);
}
// 单独遍历值 value
for (String val: map.values()) {
for (String val : map.values()) {
System.out.println(val);
}
```
```csharp title="hash_map.cs"
/* 遍历哈希表 */
// 遍历键值对 Key->Value
// 遍历键值对 key->value
foreach (var kv in map) {
Console.WriteLine(kv.Key + " -> " + kv.Value);
}
// 单独遍历键 key
foreach (int key in map.Keys) {
Console.WriteLine(key);
}
// 单独遍历值 value
foreach (string val in map.Values) {
Console.WriteLine(val);
@@ -327,10 +331,12 @@ foreach (string val in map.Values) {
for key, value := range hmap {
fmt.Println(key, "->", value)
}
// 单独遍历键 key
for key := range hmap {
fmt.Println(key)
}
// 单独遍历值 value
for _, value := range hmap {
fmt.Println(value)
@@ -339,15 +345,17 @@ for _, value := range hmap {
```swift title="hash_map.swift"
/* 遍历哈希表 */
// 遍历键值对 Key->Value
// 遍历键值对 key->value
for (key, value) in map {
print("\(key) -> \(value)")
}
// 单独遍历键 Key
// 单独遍历键 key
for key in map.keys {
print(key)
}
// 单独遍历值 Value
// 单独遍历值 value
for value in map.values {
print(value)
}
@@ -355,15 +363,17 @@ for value in map.values {
```javascript title="hash_map.js"
/* 遍历哈希表 */
console.info('\n遍历键值对 Key->Value');
// 遍历键值对 key->value
for (const [k, v] of map.entries()) {
console.info(k + ' -> ' + v);
}
console.info('\n单独遍历键 Key');
// 单独遍历键 key
for (const k of map.keys()) {
console.info(k);
}
console.info('\n单独遍历值 Value');
// 单独遍历值 value
for (const v of map.values()) {
console.info(v);
}
@@ -371,15 +381,17 @@ for (const v of map.values()) {
```typescript title="hash_map.ts"
/* 遍历哈希表 */
console.info('\n遍历键值对 Key->Value');
// 遍历键值对 key->value
for (const [k, v] of map.entries()) {
console.info(k + ' -> ' + v);
}
console.info('\n单独遍历键 Key');
// 单独遍历键 key
for (const k of map.keys()) {
console.info(k);
}
console.info('\n单独遍历值 Value');
// 单独遍历值 value
for (const v of map.values()) {
console.info(v);
}
@@ -387,35 +399,29 @@ for (const v of map.values()) {
```dart title="hash_map.dart"
/* 遍历哈希表 */
// 遍历键值对 Key->Value
map.forEach((key, value) {
print('$key -> $value');
});
// 遍历键值对 key->value
map.forEach((key, value) => print("$key -> $value"));
// 单独遍历键 Key
map.keys.forEach((key) {
print(key);
});
// 单独遍历键 key
map.keys.forEach((key) => print(key));
// 单独遍历值 Value
map.values.forEach((value) {
print(value);
});
// 单独遍历值 value
map.values.forEach((value) => print(value));
```
```rust title="hash_map.rs"
/* 遍历哈希表 */
// 遍历键值对 Key->Value
// 遍历哈希表
// 遍历键值对 key->value
for (key, value) in &map {
println!("{key} -> {value}");
}
// 单独遍历键 Key
// 单独遍历键 key
for key in map.keys() {
println!("{key}");
}
// 单独遍历值 Value
// 单独遍历值 value
for value in map.values() {
println!("{value}");
}
@@ -431,10 +437,12 @@ for value in map.values() {
for ((key, value) in map) {
println("$key -> $value")
}
// 单独遍历键 key
for (key in map.keys) {
println(key)
}
// 单独遍历值 value
for (_val in map.values) {
println(_val)
@@ -454,4 +462,4 @@ hmap.values.each { |val| puts val }
```
<!-- [tutor]{hash_map_traversal_tutor} -->
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B7%BB%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E9%94%AE%E5%80%BC%E5%AF%B9%20key-%3Evalue%0A%20%20%20%20for%20key,%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key,%20%22-%3E%22,%20value%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E9%94%AE%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E5%80%BC%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20%E6%B7%BB%E5%8A%A0%E6%93%8D%E4%BD%9C%0A%20%20%20%20%23%20%E5%9C%A8%E5%93%88%E5%B8%8C%E8%A1%A8%E4%B8%AD%E6%B7%BB%E5%8A%A0%E9%94%AE%E5%80%BC%E5%AF%B9%20%28key,%20value%29%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E5%93%88%E5%B8%8C%E8%A1%A8%0A%20%20%20%20%23%20%E9%81%8D%E5%8E%86%E9%94%AE%E5%80%BC%E5%AF%B9%20key-%3Evalue%0A%20%20%20%20for%20key,%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key,%20%22-%3E%22,%20value%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E9%94%AE%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20%E5%8D%95%E7%8B%AC%E9%81%8D%E5%8E%86%E5%80%BC%20value%0A%20%20%20%20for%20val%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28val%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false

View File

@@ -17,15 +17,15 @@ heapq.heappush(max_heap, flag * 5)
heapq.heappush(max_heap, flag * 4)
# 获取堆顶元素
peek: int = flag * max_heap[0] # 5
peek: int = flag * max_heap[0] # 5
# 堆顶元素出堆
# 出堆元素会形成一个从大到小的序列
val = flag * heapq.heappop(max_heap) # 5
val = flag * heapq.heappop(max_heap) # 4
val = flag * heapq.heappop(max_heap) # 3
val = flag * heapq.heappop(max_heap) # 2
val = flag * heapq.heappop(max_heap) # 1
val = flag * heapq.heappop(max_heap) # 5
val = flag * heapq.heappop(max_heap) # 4
val = flag * heapq.heappop(max_heap) # 3
val = flag * heapq.heappop(max_heap) # 2
val = flag * heapq.heappop(max_heap) # 1
# 获取堆大小
size: int = len(max_heap)
@@ -34,6 +34,7 @@ size: int = len(max_heap)
is_empty: bool = not max_heap
# 输入列表并建堆
# 时间复杂度为 O(n) ,而非 O(nlogn)
min_heap: list[int] = [1, 3, 2, 5, 4]
heapq.heapify(min_heap)
```
@@ -70,6 +71,7 @@ int size = maxHeap.size();
bool isEmpty = maxHeap.empty();
/* 输入列表并建堆 */
// 时间复杂度为 O(n) ,而非 O(nlogn)
vector<int> input{1, 3, 2, 5, 4};
minHeap = priority_queue<int, vector<int>, greater<int>>(input.begin(), input.end());
```
@@ -106,6 +108,7 @@ int size = maxHeap.size();
boolean isEmpty = maxHeap.isEmpty();
/* 输入列表并建堆 */
// 时间复杂度为 O(n) ,而非 O(nlogn)
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
```
@@ -124,15 +127,15 @@ maxHeap.Enqueue(5, 5);
maxHeap.Enqueue(4, 4);
/* 获取堆顶元素 */
int peek = maxHeap.Peek();//5
int peek = maxHeap.Peek(); // 5
/* 堆顶元素出堆 */
// 出堆元素会形成一个从大到小的序列
peek = maxHeap.Dequeue(); // 5
peek = maxHeap.Dequeue(); // 4
peek = maxHeap.Dequeue(); // 3
peek = maxHeap.Dequeue(); // 2
peek = maxHeap.Dequeue(); // 1
peek = maxHeap.Dequeue(); // 5
peek = maxHeap.Dequeue(); // 4
peek = maxHeap.Dequeue(); // 3
peek = maxHeap.Dequeue(); // 2
peek = maxHeap.Dequeue(); // 1
/* 获取堆大小 */
int size = maxHeap.Count;
@@ -141,6 +144,7 @@ int size = maxHeap.Count;
bool isEmpty = maxHeap.Count == 0;
/* 输入列表并建堆 */
// 时间复杂度为 O(n) ,而非 O(nlogn)
minHeap = new PriorityQueue<int, int>([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]);
```
@@ -149,14 +153,14 @@ minHeap = new PriorityQueue<int, int>([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]);
// 实现 heap.Interface 需要同时实现 sort.Interface
type intHeap []any
// Push heap.Interface 的方法,实现推入元素到堆
// Push heap.Interface 的函数,实现推入元素到堆
func (h *intHeap) Push(x any) {
// Push 和 Pop 使用 pointer receiver 作为参数
// 因为它们不仅会对切片的内容进行调整,还会修改切片的长度。
*h = append(*h, x.(int))
}
// Pop heap.Interface 的方法,实现弹出堆顶元素
// Pop heap.Interface 的函数,实现弹出堆顶元素
func (h *intHeap) Pop() any {
// 待出堆元素存放在最后
last := (*h)[len(*h)-1]
@@ -164,18 +168,18 @@ func (h *intHeap) Pop() any {
return last
}
// Len sort.Interface 的方法
// Len sort.Interface 的函数
func (h *intHeap) Len() int {
return len(*h)
}
// Less sort.Interface 的方法
// Less sort.Interface 的函数
func (h *intHeap) Less(i, j int) bool {
// 如果实现小顶堆,则需要调整为小于号
return (*h)[i].(int) > (*h)[j].(int)
}
// Swap sort.Interface 的方法
// Swap sort.Interface 的函数
func (h *intHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
@@ -185,31 +189,31 @@ func (h *intHeap) Top() any {
return (*h)[0]
}
/* Driver Code */
func TestHeap(t *testing.T) {
/* 初始化堆 */
// 初始化大顶堆
maxHeap := &intHeap{}
heap.Init(maxHeap)
/* 元素入堆 */
// 调用 heap.Interface 的方法,来添加元素
// 调用 heap.Interface 的函数,来添加元素
heap.Push(maxHeap, 1)
heap.Push(maxHeap, 3)
heap.Push(maxHeap, 2)
heap.Push(maxHeap, 4)
heap.Push(maxHeap, 5)
heap.Push(maxHeap, 4)
PrintHeap(*maxHeap)
/* 获取堆顶元素 */
top := maxHeap.Top()
fmt.Printf("堆顶元素为 %d\n", top)
/* 堆顶元素出堆 */
// 调用 heap.Interface 的方法,来移除元素
heap.Pop(maxHeap) // 5
heap.Pop(maxHeap) // 4
heap.Pop(maxHeap) // 3
heap.Pop(maxHeap) // 2
heap.Pop(maxHeap) // 1
// 调用 heap.Interface 的函数,来移除元素
fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 5
fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 4
fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 3
fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 2
fmt.Printf("出堆元素为 %d\n", heap.Pop(maxHeap)) // 1
/* 获取堆大小 */
size := len(*maxHeap)
@@ -222,8 +226,10 @@ func TestHeap(t *testing.T) {
```
```swift title="heap.swift"
import HeapModule
/* 初始化堆 */
// Swift 的 Heap 类型同时支持最大堆和最小堆,且需要引入 swift-collections
// Swift 的 Heap 类型同时支持大顶堆和小顶堆,需要引入 swift-collections 包
var heap = Heap<Int>()
/* 元素入堆 */
@@ -234,7 +240,7 @@ heap.insert(5)
heap.insert(4)
/* 获取堆顶元素 */
var peek = heap.max()!
var peek = heap.max()
/* 堆顶元素出堆 */
peek = heap.removeMax() // 5
@@ -250,6 +256,7 @@ let size = heap.count
let isEmpty = heap.isEmpty
/* 输入列表并建堆 */
// 时间复杂度为 O(n) ,而非 O(nlogn)
let heap2 = Heap([1, 3, 2, 5, 4])
```
@@ -266,12 +273,13 @@ let heap2 = Heap([1, 3, 2, 5, 4])
```
```rust title="heap.rs"
use std::collections::BinaryHeap;
use std::cmp::Reverse;
use std::{cmp::Reverse, collections::BinaryHeap};
/* 初始化堆 */
// 初始化小顶堆
let mut min_heap = BinaryHeap::<Reverse<i32>>::new();
// Rust 的 BinaryHeap 是大顶堆,小顶堆需用 Reverse 包装元素
#[allow(unused_assignments)]
let mut min_heap = BinaryHeap::new();
// 初始化大顶堆
let mut max_heap = BinaryHeap::new();
@@ -283,15 +291,15 @@ max_heap.push(5);
max_heap.push(4);
/* 获取堆顶元素 */
let peek = max_heap.peek().unwrap(); // 5
let peek = max_heap.peek().unwrap(); // 5
/* 堆顶元素出堆 */
// 出堆元素会形成一个从大到小的序列
let peek = max_heap.pop().unwrap(); // 5
let peek = max_heap.pop().unwrap(); // 4
let peek = max_heap.pop().unwrap(); // 3
let peek = max_heap.pop().unwrap(); // 2
let peek = max_heap.pop().unwrap(); // 1
let peek = max_heap.pop().unwrap(); // 5
let peek = max_heap.pop().unwrap(); // 4
let peek = max_heap.pop().unwrap(); // 3
let peek = max_heap.pop().unwrap(); // 2
let peek = max_heap.pop().unwrap(); // 1
/* 获取堆大小 */
let size = max_heap.len();
@@ -300,7 +308,8 @@ let size = max_heap.len();
let is_empty = max_heap.is_empty();
/* 输入列表并建堆 */
let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]);
// 时间复杂度为 O(n) ,而非 O(nlogn)
min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]);
```
```c title="heap.c"
@@ -339,7 +348,8 @@ val size = maxHeap.size
val isEmpty = maxHeap.isEmpty()
/* 输入列表并建堆 */
minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4))
// 时间复杂度为 O(n) ,而非 O(nlogn)
minHeap = PriorityQueue(mutableListOf<Int?>(1, 3, 2, 5, 4))
```
```ruby title="heap.rb"
@@ -347,4 +357,4 @@ minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4))
```
<!-- [tutor]{heap_operations_tutor} -->
https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20min_heap,%20flag%20%3D%20%5B%5D,%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20max_heap,%20flag%20%3D%20%5B%5D,%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E5%9D%97%E9%BB%98%E8%AE%A4%E5%AE%9E%E7%8E%B0%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E8%80%83%E8%99%91%E5%B0%86%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B4%9F%E2%80%9D%E5%90%8E%E5%86%8D%E5%85%A5%E5%A0%86%EF%BC%8C%E8%BF%99%E6%A0%B7%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%86%E5%A4%A7%E5%B0%8F%E5%85%B3%E7%B3%BB%E9%A2%A0%E5%80%92%EF%BC%8C%E4%BB%8E%E8%80%8C%E5%AE%9E%E7%8E%B0%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%B0%8F%E9%A1%B6%E5%A0%86%EF%BC%8Cflag%20%3D%20-1%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%201%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%203%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%202%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%205%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20*%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20*%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E5%85%83%E7%B4%A0%E4%BC%9A%E5%BD%A2%E6%88%90%E4%B8%80%E4%B8%AA%E4%BB%8E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20*%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E5%A0%86%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BE%93%E5%85%A5%E5%88%97%E8%A1%A8%E5%B9%B6%E5%BB%BA%E5%A0%86%0A%20%20%20%20min_heap%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20min_heap,%20flag%20%3D%20%5B%5D,%201%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20max_heap,%20flag%20%3D%20%5B%5D,%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%20%E7%9A%84%20heapq%20%E6%A8%A1%E5%9D%97%E9%BB%98%E8%AE%A4%E5%AE%9E%E7%8E%B0%E5%B0%8F%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E8%80%83%E8%99%91%E5%B0%86%E2%80%9C%E5%85%83%E7%B4%A0%E5%8F%96%E8%B4%9F%E2%80%9D%E5%90%8E%E5%86%8D%E5%85%A5%E5%A0%86%EF%BC%8C%E8%BF%99%E6%A0%B7%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%B0%86%E5%A4%A7%E5%B0%8F%E5%85%B3%E7%B3%BB%E9%A2%A0%E5%80%92%EF%BC%8C%E4%BB%8E%E8%80%8C%E5%AE%9E%E7%8E%B0%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%23%20%E5%9C%A8%E6%9C%AC%E7%A4%BA%E4%BE%8B%E4%B8%AD%EF%BC%8Cflag%20%3D%201%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%B0%8F%E9%A1%B6%E5%A0%86%EF%BC%8Cflag%20%3D%20-1%20%E6%97%B6%E5%AF%B9%E5%BA%94%E5%A4%A7%E9%A1%B6%E5%A0%86%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%85%83%E7%B4%A0%E5%85%A5%E5%A0%86%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap,%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%A0%86%E9%A1%B6%E5%85%83%E7%B4%A0%E5%87%BA%E5%A0%86%0A%20%20%20%20%23%20%E5%87%BA%E5%A0%86%E5%85%83%E7%B4%A0%E4%BC%9A%E5%BD%A2%E6%88%90%E4%B8%80%E4%B8%AA%E4%BB%8E%E5%A4%A7%E5%88%B0%E5%B0%8F%E7%9A%84%E5%BA%8F%E5%88%97%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%8E%B7%E5%8F%96%E5%A0%86%E5%A4%A7%E5%B0%8F%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20%E5%88%A4%E6%96%AD%E5%A0%86%E6%98%AF%E5%90%A6%E4%B8%BA%E7%A9%BA%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20%E8%BE%93%E5%85%A5%E5%88%97%E8%A1%A8%E5%B9%B6%E5%BB%BA%E5%A0%86%0A%20%20%20%20%23%20%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6%E4%B8%BA%20O%28n%29%20%EF%BC%8C%E8%80%8C%E9%9D%9E%20O%28nlogn%29%0A%20%20%20%20min_heap%20%3D%20%5B1,%203,%202,%205,%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false

View File

@@ -6,7 +6,7 @@ from collections import deque
deq: deque[int] = deque()
# 元素入队
deq.append(2) # 添加至队尾
deq.append(2) # 添加至队尾
deq.append(5)
deq.append(4)
deq.appendleft(3) # 添加至队首
@@ -18,7 +18,7 @@ rear: int = deq[-1] # 队尾元素
# 元素出队
pop_front: int = deq.popleft() # 队首元素出队
pop_rear: int = deq.pop() # 队尾元素出队
pop_rear: int = deq.pop() # 队尾元素出队
# 获取双向队列的长度
size: int = len(deq)
@@ -32,19 +32,19 @@ is_empty: bool = len(deq) == 0
deque<int> deque;
/* 元素入队 */
deque.push_back(2); // 添加至队尾
deque.push_back(2); // 添加至队尾
deque.push_back(5);
deque.push_back(4);
deque.push_front(3); // 添加至队首
deque.push_front(3); // 添加至队首
deque.push_front(1);
/* 访问元素 */
int front = deque.front(); // 队首元素
int back = deque.back(); // 队尾元素
int back = deque.back(); // 队尾元素
/* 元素出队 */
deque.pop_front(); // 队首元素出队
deque.pop_back(); // 队尾元素出队
deque.pop_front(); // 队首元素出队
deque.pop_back(); // 队尾元素出队
/* 获取双向队列的长度 */
int size = deque.size();
@@ -58,19 +58,19 @@ bool empty = deque.empty();
Deque<Integer> deque = new LinkedList<>();
/* 元素入队 */
deque.offerLast(2); // 添加至队尾
deque.offerLast(2); // 添加至队尾
deque.offerLast(5);
deque.offerLast(4);
deque.offerFirst(3); // 添加至队首
deque.offerFirst(3); // 添加至队首
deque.offerFirst(1);
/* 访问元素 */
int peekFirst = deque.peekFirst(); // 队首元素
int peekLast = deque.peekLast(); // 队尾元素
int peekFirst = deque.peekFirst(); // 队首元素
int peekLast = deque.peekLast(); // 队尾元素
/* 元素出队 */
int popFirst = deque.pollFirst(); // 队首元素出队
int popLast = deque.pollLast(); // 队尾元素出队
int popFirst = deque.pollFirst(); // 队首元素出队
int popLast = deque.pollLast(); // 队尾元素出队
/* 获取双向队列的长度 */
int size = deque.size();
@@ -81,7 +81,7 @@ boolean isEmpty = deque.isEmpty();
```csharp title="deque.cs"
/* 初始化双向队列 */
// 在 C# 中,将链表 LinkedList 看作双向队列来使用
// 在 C# 中,将链表 LinkedList 当作双向队列来使用
LinkedList<int> deque = new();
/* 元素入队 */
@@ -92,8 +92,8 @@ deque.AddFirst(3); // 添加至队首
deque.AddFirst(1);
/* 访问元素 */
int peekFirst = deque.First.Value; // 队首元素
int peekLast = deque.Last.Value; // 队尾元素
int? peekFirst = deque.First?.Value; // 队首元素
int? peekLast = deque.Last?.Value; // 队尾元素
/* 元素出队 */
deque.RemoveFirst(); // 队首元素出队
@@ -112,19 +112,19 @@ bool isEmpty = deque.Count == 0;
deque := list.New()
/* 元素入队 */
deque.PushBack(2) // 添加至队尾
deque.PushBack(2) // 添加至队尾
deque.PushBack(5)
deque.PushBack(4)
deque.PushFront(3) // 添加至队首
deque.PushFront(3) // 添加至队首
deque.PushFront(1)
/* 访问元素 */
front := deque.Front() // 队首元素
rear := deque.Back() // 队尾元素
rear := deque.Back() // 队尾元素
/* 元素出队 */
deque.Remove(front) // 队首元素出队
deque.Remove(rear) // 队尾元素出队
deque.Remove(front) // 队首元素出队
deque.Remove(rear) // 队尾元素出队
/* 获取双向队列的长度 */
size := deque.Len()
@@ -150,7 +150,7 @@ let peekFirst = deque.first! // 队首元素
let peekLast = deque.last! // 队尾元素
/* 元素出队 */
// 使用 Array 模拟时 popFirst 的复杂度为 O(n)
// 使用 Array 模拟时 removeFirst 的复杂度为 O(n)
let popFirst = deque.removeFirst() // 队首元素出队
let popLast = deque.removeLast() // 队尾元素出队
@@ -222,57 +222,53 @@ const isEmpty: boolean = size === 0;
```dart title="deque.dart"
/* 初始化双向队列 */
// 在 Dart 中,Queue 被定义为双向队列
Queue<int> deque = Queue<int>();
final Queue<int> deque = Queue();
/* 元素入队 */
deque.addLast(2); // 添加至队尾
deque.addLast(2); // 添加至队尾
deque.addLast(5);
deque.addLast(4);
deque.addFirst(3); // 添加至队首
deque.addFirst(1);
/* 访问元素 */
int peekFirst = deque.first; // 队首元素
int peekLast = deque.last; // 队尾元素
final int peekFirst = deque.first; // 队首元素
final int peekLast = deque.last; // 队尾元素
/* 元素出队 */
int popFirst = deque.removeFirst(); // 队首元素出队
int popLast = deque.removeLast(); // 队尾元素出队
final int popFirst = deque.removeFirst(); // 队首元素出队
final int popLast = deque.removeLast(); // 队尾元素出队
/* 获取双向队列的长度 */
int size = deque.length;
final int size = deque.length;
/* 判断双向队列是否为空 */
bool isEmpty = deque.isEmpty;
final bool isEmpty = deque.isEmpty;
```
```rust title="deque.rs"
/* 初始化双向队列 */
let mut deque: VecDeque<u32> = VecDeque::new();
// 初始化双向队列
let mut deque: VecDeque<i32> = VecDeque::new();
/* 元素入队 */
deque.push_back(2); // 添加至队尾
deque.push_back(2); // 添加至队尾
deque.push_back(5);
deque.push_back(4);
deque.push_front(3); // 添加至队首
deque.push_front(1);
/* 访问元素 */
if let Some(front) = deque.front() { // 队首元素
}
if let Some(rear) = deque.back() { // 队尾元素
}
// 访问元素
let peek_first = deque.front().unwrap(); // 队首元素
let peek_last = deque.back().unwrap(); // 队尾元素
/* 元素出队 */
if let Some(pop_front) = deque.pop_front() { // 队首元素出队
}
if let Some(pop_rear) = deque.pop_back() { // 队尾元素出队
}
// 元素出队
let pop_first = deque.pop_front().unwrap(); // 队首元素出队
let pop_last = deque.pop_back().unwrap(); // 队尾元素出队
/* 获取双向队列的长度 */
// 获取双向队列的长度
let size = deque.len();
/* 判断双向队列是否为空 */
// 判断双向队列是否为空
let is_empty = deque.is_empty();
```
@@ -285,7 +281,7 @@ let is_empty = deque.is_empty();
val deque = LinkedList<Int>()
/* 元素入队 */
deque.offerLast(2) // 添加至队尾
deque.offerLast(2) // 添加至队尾
deque.offerLast(5)
deque.offerLast(4)
deque.offerFirst(3) // 添加至队首
@@ -293,11 +289,11 @@ deque.offerFirst(1)
/* 访问元素 */
val peekFirst = deque.peekFirst() // 队首元素
val peekLast = deque.peekLast() // 队尾元素
val peekLast = deque.peekLast() // 队尾元素
/* 元素出队 */
val popFirst = deque.pollFirst() // 队首元素出队
val popLast = deque.pollLast() // 队尾元素出队
val popLast = deque.pollLast() // 队尾元素出队
/* 获取双向队列的长度 */
val size = deque.size
@@ -308,10 +304,10 @@ val isEmpty = deque.isEmpty()
```ruby title="deque.rb"
# 初始化双向队列
# Ruby 没有内直的双端队列,只能把 Array 当作双端队列来使用
# Ruby 没有内置的双端队列,只能把 Array 当作双端队列来使用
deque = []
# 元素如队
# 元素入队
deque << 2
deque << 5
deque << 4
@@ -324,7 +320,7 @@ peek_first = deque.first
peek_last = deque.last
# 元素出队
# 请注意,由于是数组, Array#shift 方法的时间复杂度为 O(n)
# 请注意,由于是数组,Array#shift 方法的时间复杂度为 O(n)
pop_front = deque.shift
pop_back = deque.pop

View File

@@ -141,7 +141,7 @@ queue.append(4)
let peek = queue.first!
/* 元素出队 */
// 由于是数组,因此 removeFirst 的复杂度为 O(n)
// 使用 Array 模拟时 removeFirst 的复杂度为 O(n)
let pop = queue.removeFirst()
/* 获取队列的长度 */
@@ -174,7 +174,7 @@ const pop = queue.shift();
const size = queue.length;
/* 判断队列是否为空 */
const empty = queue.length === 0;
const isEmpty = queue.length === 0;
```
```typescript title="queue.ts"
@@ -200,13 +200,13 @@ const pop = queue.shift();
const size = queue.length;
/* 判断队列是否为空 */
const empty = queue.length === 0;
const isEmpty = queue.length === 0;
```
```dart title="queue.dart"
/* 初始化队列 */
// 在 Dart 中,队列类 Queue 是双向队列,也可作为队列使用
Queue<int> queue = Queue();
// 在 Dart 中,一般将双向队列类 Queue 当作队列使用
final Queue<int> queue = Queue();
/* 元素入队 */
queue.add(1);
@@ -216,43 +216,41 @@ queue.add(5);
queue.add(4);
/* 访问队首元素 */
int peek = queue.first;
final int peek = queue.first;
/* 元素出队 */
int pop = queue.removeFirst();
final int pop = queue.removeFirst();
/* 获取队列的长度 */
int size = queue.length;
final int size = queue.length;
/* 判断队列是否为空 */
bool isEmpty = queue.isEmpty;
final bool isEmpty = queue.isEmpty;
```
```rust title="queue.rs"
/* 初始化双向队列 */
// 在 Rust 中使用双向队列作为普通队列来使用
let mut deque: VecDeque<u32> = VecDeque::new();
// 初始化队列
// 在 Rust 中,一般将双向队列 VecDeque 看作队列使用
let mut queue: VecDeque<i32> = VecDeque::new();
/* 元素入队 */
deque.push_back(1);
deque.push_back(3);
deque.push_back(2);
deque.push_back(5);
deque.push_back(4);
// 元素入队
queue.push_back(1);
queue.push_back(3);
queue.push_back(2);
queue.push_back(5);
queue.push_back(4);
/* 访问队首元素 */
if let Some(front) = deque.front() {
}
// 访问队首元素
let peek = queue.front().unwrap();
/* 元素出队 */
if let Some(pop) = deque.pop_front() {
}
// 元素出队
let pop = queue.pop_front().unwrap();
/* 获取队列的长度 */
let size = deque.len();
// 获取队列的长度
let size = queue.len();
/* 判断队列是否为空 */
let is_empty = deque.is_empty();
// 判断队列是否为空
let is_empty = queue.is_empty();
```
```c title="queue.c"
@@ -285,7 +283,7 @@ val isEmpty = queue.isEmpty()
```ruby title="queue.rb"
# 初始化队列
# Ruby 内置的队列(Thread::Queue) 没有 peek 和遍历方法,可以把 Array 当作队列来使用
# Ruby 内置的队列(Thread::Queue)没有 peek 和遍历方法,可以把 Array 当作队列来使用
queue = []
# 元素入队
@@ -299,7 +297,7 @@ queue.push(4)
peek = queue.first
# 元素出队
# 清注意,由于是数组,Array#shift 方法时间复杂度为 O(n)
# 请注意,由于是数组,Array#shift 方法的时间复杂度为 O(n)
pop = queue.shift
# 获取队列的长度

View File

@@ -160,7 +160,7 @@ stack.push(5);
stack.push(4);
/* 访问栈顶元素 */
const peek = stack[stack.length-1];
const peek = stack[stack.length - 1];
/* 元素出栈 */
const pop = stack.pop();
@@ -169,7 +169,7 @@ const pop = stack.pop();
const size = stack.length;
/* 判断是否为空 */
const is_empty = stack.length === 0;
const isEmpty = stack.length === 0;
```
```typescript title="stack.ts"
@@ -194,13 +194,13 @@ const pop = stack.pop();
const size = stack.length;
/* 判断是否为空 */
const is_empty = stack.length === 0;
const isEmpty = stack.length === 0;
```
```dart title="stack.dart"
/* 初始化栈 */
// Dart 没有内置的栈类,可以把 List 当作栈来使用
List<int> stack = [];
final List<int> stack = [];
/* 元素入栈 */
stack.add(1);
@@ -210,40 +210,40 @@ stack.add(5);
stack.add(4);
/* 访问栈顶元素 */
int peek = stack.last;
final int peek = stack.last;
/* 元素出栈 */
int pop = stack.removeLast();
final int pop = stack.removeLast();
/* 获取栈的长度 */
int size = stack.length;
final int size = stack.length;
/* 判断是否为空 */
bool isEmpty = stack.isEmpty;
final bool isEmpty = stack.isEmpty;
```
```rust title="stack.rs"
/* 初始化栈 */
// 把 Vec 当作栈来使用
// 初始化栈
// 在 Rust 中,推荐将 Vec 当作栈来使用
let mut stack: Vec<i32> = Vec::new();
/* 元素入栈 */
// 元素入栈
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
/* 访问栈顶元素 */
let top = stack.last().unwrap();
// 访问栈顶元素
let peek = stack.last().unwrap();
/* 元素出栈 */
// 元素出栈
let pop = stack.pop().unwrap();
/* 获取栈的长度 */
// 获取栈的长度
let size = stack.len();
/* 判断是否为空 */
// 判断栈是否为空
let is_empty = stack.is_empty();
```

View File

@@ -133,7 +133,6 @@ impl TreeNode {
/* 二叉树节点结构体 */
typedef struct TreeNode {
int val; // 节点值
int height; // 节点高度
struct TreeNode *left; // 左子节点指针
struct TreeNode *right; // 右子节点指针
} TreeNode;
@@ -144,7 +143,6 @@ TreeNode *newTreeNode(int val) {
node = (TreeNode *)malloc(sizeof(TreeNode));
node->val = val;
node->height = 0;
node->left = NULL;
node->right = NULL;
return node;
@@ -191,11 +189,11 @@ n2.right = n5
```cpp title="binary_tree.cpp"
/* 初始化二叉树 */
// 初始化节点
TreeNode* n1 = new TreeNode(1);
TreeNode* n2 = new TreeNode(2);
TreeNode* n3 = new TreeNode(3);
TreeNode* n4 = new TreeNode(4);
TreeNode* n5 = new TreeNode(5);
TreeNode *n1 = new TreeNode(1);
TreeNode *n2 = new TreeNode(2);
TreeNode *n3 = new TreeNode(3);
TreeNode *n4 = new TreeNode(4);
TreeNode *n5 = new TreeNode(5);
// 构建节点之间的引用(指针)
n1->left = n2;
n1->right = n3;
@@ -204,6 +202,7 @@ n2->right = n5;
```
```java title="binary_tree.java"
/* 初始化二叉树 */
// 初始化节点
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
@@ -248,6 +247,7 @@ n2.Right = n5
```
```swift title="binary_tree.swift"
/* 初始化二叉树 */
// 初始化节点
let n1 = TreeNode(x: 1)
let n2 = TreeNode(x: 2)
@@ -294,11 +294,11 @@ n2.right = n5;
```dart title="binary_tree.dart"
/* 初始化二叉树 */
// 初始化节点
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
TreeNode n1 = TreeNode(1);
TreeNode n2 = TreeNode(2);
TreeNode n3 = TreeNode(3);
TreeNode n4 = TreeNode(4);
TreeNode n5 = TreeNode(5);
// 构建节点之间的引用(指针)
n1.left = n2;
n1.right = n3;
@@ -307,6 +307,7 @@ n2.right = n5;
```
```rust title="binary_tree.rs"
/* 初始化二叉树 */
// 初始化节点
let n1 = TreeNode::new(1);
let n2 = TreeNode::new(2);
@@ -314,10 +315,10 @@ let n3 = TreeNode::new(3);
let n4 = TreeNode::new(4);
let n5 = TreeNode::new(5);
// 构建节点之间的引用(指针)
n1.borrow_mut().left = Some(n2.clone());
n1.borrow_mut().right = Some(n3);
n2.borrow_mut().left = Some(n4);
n2.borrow_mut().right = Some(n5);
n1.borrow_mut().left = Some(Rc::clone(&n2));
n1.borrow_mut().right = Some(Rc::clone(&n3));
n2.borrow_mut().left = Some(Rc::clone(&n4));
n2.borrow_mut().right = Some(Rc::clone(&n5));
```
```c title="binary_tree.c"
@@ -336,6 +337,7 @@ n2->right = n5;
```
```kotlin title="binary_tree.kt"
/* 初始化二叉树 */
// 初始化节点
val n1 = TreeNode(1)
val n2 = TreeNode(2)
@@ -370,27 +372,27 @@ https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%2
<!-- [snippet]{insert_remove_node} -->
```python title="binary_tree.py"
# 插入与删除节点
p = TreeNode(0)
P = TreeNode(0)
# 在 n1 -> n2 中间插入节点 P
n1.left = p
p.left = n2
n1.left = P
P.left = n2
# 删除节点 P
n1.left = n2
```
```cpp title="binary_tree.cpp"
/* 插入与删除节点 */
TreeNode* P = new TreeNode(0);
TreeNode *P = new TreeNode(0);
// 在 n1 -> n2 中间插入节点 P
n1->left = P;
P->left = n2;
// 删除节点 P
n1->left = n2;
// 释放内存
delete P;
delete P; // 释放内存
```
```java title="binary_tree.java"
/* 插入与删除节点 */
TreeNode P = new TreeNode(0);
// 在 n1 -> n2 中间插入节点 P
n1.left = P;
@@ -420,6 +422,7 @@ n1.Left = n2
```
```swift title="binary_tree.swift"
/* 插入与删除节点 */
let P = TreeNode(x: 0)
// 在 n1 -> n2 中间插入节点 P
n1.left = P
@@ -430,7 +433,7 @@ n1.left = n2
```javascript title="binary_tree.js"
/* 插入与删除节点 */
let P = new TreeNode(0);
const P = new TreeNode(0);
// 在 n1 -> n2 中间插入节点 P
n1.left = P;
P.left = n2;
@@ -450,21 +453,23 @@ n1.left = n2;
```dart title="binary_tree.dart"
/* 插入与删除节点 */
TreeNode P = new TreeNode(0);
TreeNode p = TreeNode(0);
// 在 n1 -> n2 中间插入节点 P
n1.left = P;
P.left = n2;
n1.left = p;
p.left = n2;
// 删除节点 P
n1.left = n2;
```
```rust title="binary_tree.rs"
/* 插入与删除节点 */
let p = TreeNode::new(0);
// 在 n1 -> n2 中间插入节点 P
n1.borrow_mut().left = Some(p.clone());
p.borrow_mut().left = Some(n2.clone());
// 删除节点 p
n1.borrow_mut().left = Some(n2);
p.borrow_mut().left = Some(Rc::clone(&n2));
n1.borrow_mut().left = Some(Rc::clone(&p));
// 删除节点 P
drop(p);
n1.borrow_mut().left = Some(Rc::clone(&n2));
```
```c title="binary_tree.c"
@@ -480,6 +485,7 @@ free(P);
```
```kotlin title="binary_tree.kt"
/* 插入与删除节点 */
val P = TreeNode(0)
// 在 n1 -> n2 中间插入节点 P
n1.left = P
@@ -499,4 +505,4 @@ n1.left = n2
```
<!-- [tutor]{insert_remove_node_tutor} -->
https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22%E4%BA%8C%E5%8F%89%E6%A0%91%E8%8A%82%E7%82%B9%E7%B1%BB%22%22%22%0A%20%20%20%20def%20__init__%28self,%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20%E8%8A%82%E7%82%B9%E5%80%BC%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20%E5%B7%A6%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20%E5%8F%B3%E5%AD%90%E8%8A%82%E7%82%B9%E5%BC%95%E7%94%A8%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E4%BA%8C%E5%8F%89%E6%A0%91%0A%20%20%20%20%23%20%E5%88%9D%E5%A7%8B%E5%8C%96%E8%8A%82%E7%82%B9%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20%E6%9E%84%E5%BB%BA%E8%8A%82%E7%82%B9%E4%B9%8B%E9%97%B4%E7%9A%84%E5%BC%95%E7%94%A8%EF%BC%88%E6%8C%87%E9%92%88%EF%BC%89%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20%E6%8F%92%E5%85%A5%E4%B8%8E%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%0A%20%20%20%20P%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20%E5%9C%A8%20n1%20-%3E%20n2%20%E4%B8%AD%E9%97%B4%E6%8F%92%E5%85%A5%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20P%0A%20%20%20%20P.left%20%3D%20n2%0A%20%20%20%20%23%20%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false

View File

@@ -27,7 +27,7 @@ enum Deque {
print("队尾元素 peekLast = \(peekLast)")
/* 元素出队 */
// 使用 Array 模拟时 popFirst 的复杂度为 O(n)
// 使用 Array 模拟时 removeFirst 的复杂度为 O(n)
let popFirst = deque.removeFirst()
print("队首出队元素 popFirst = \(popFirst),队首出队后 deque = \(deque)")
let popLast = deque.removeLast()

View File

@@ -25,7 +25,7 @@ enum Queue {
print("队首元素 peek = \(peek)")
/* 元素出队 */
// 使用 Array 模拟时 pop 的复杂度为 O(n)
// 使用 Array 模拟时 removeFirst 的复杂度为 O(n)
let pop = queue.removeFirst()
print("出队元素 pop = \(pop),出队后 queue = \(queue)")

View File

@@ -6,8 +6,8 @@
/* 双向链表节点 */
class ListNode {
prev: ListNode; // 前驱节点引用 (指针)
next: ListNode; // 后继节点引用 (指针)
prev: ListNode | null; // 前驱节点引用 (指针)
next: ListNode | null; // 后继节点引用 (指针)
val: number; // 节点值
constructor(val: number) {

View File

@@ -75,7 +75,7 @@ int main() {
/* Initialize the array */
int size = 5;
int arr[5];
int arr[5] = {0};
printf("Array arr = ");
printArray(arr, size);

View File

@@ -123,7 +123,7 @@ int main() {
for (int i = 0; i < 10; i++) {
push(queue, i);
pop(queue);
printf("After enqueueing and dequeueing in round %d, queue = ", i);
printf("After round %d of enqueue + dequeue, queue = ", i);
printArray(toArray(queue, &queSize), queSize);
}

View File

@@ -14,7 +14,7 @@ extern "C" {
/* Linked list node structure */
typedef struct ListNode {
int val; // Node value
struct ListNode *next; // Reference to the next node
struct ListNode *next; // Pointer to the next node
} ListNode;
/* Constructor: initialize a new node */

View File

@@ -18,7 +18,7 @@ int randomAccess(int *nums, int size) {
/* Extend the array length */
int *extend(int *nums, int size, int enlarge) {
// Initialize an array with the extended length
int *res = new int[size + enlarge];
int *res = new int[size + enlarge]{};
// Copy all elements from the original array to the new array
for (int i = 0; i < size; i++) {
res[i] = nums[i];
@@ -69,7 +69,7 @@ int find(int *nums, int size, int target) {
int main() {
/* Initialize the array */
int size = 5;
int *arr = new int[size];
int *arr = new int[size]{};
cout << "Array arr = ";
printArray(arr, size);

View File

@@ -76,7 +76,7 @@ int main() {
/* Access a node */
ListNode *node = access(n0, 3);
cout << "Value of the linked list node at index 3 = " << node->val << endl;
cout << "Value of the node at index 3 in the linked list = " << node->val << endl;
/* Find a node */
int index = find(n0, 2);

View File

@@ -24,6 +24,6 @@ int main() {
size_t hashStr = hash<string>()(str);
cout << "String " << str << " has hash value " << hashStr << "\n";
// C++ std::hash provides hashing for fundamental types and selected standard-library types
// For arrays and unsupported object types, supply your own hash implementation
// In C++, the built-in std::hash() only computes hash values for basic data types
// Hashing arrays and objects requires a custom implementation
}

View File

@@ -118,7 +118,7 @@ int main() {
for (int i = 0; i < 10; i++) {
queue->push(i);
queue->pop();
cout << "Round " << i << " : after enqueue + dequeue, queue = ";
cout << "After round " << i << " of enqueue + dequeue, queue = ";
printVector(queue->toVector());
}

View File

@@ -108,7 +108,7 @@ public class array_queue {
for (int i = 0; i < 10; i++) {
queue.Push(i);
queue.Pop();
Console.WriteLine("Round " + i + " : after enqueue + dequeue, queue = " + string.Join(",", queue.ToArray()));
Console.WriteLine("After round " + i + " of enqueue + dequeue, queue = " + string.Join(",", queue.ToArray()));
}
}
}

View File

@@ -18,7 +18,7 @@ void main() {
double dec = 3.14159;
int hashDec = dec.hashCode;
print("Hash value of decimal $dec: $hashDec");
print("Floating-point number $dec has hash value $hashDec");
String str = "Hello 算法";
int hashStr = str.hashCode;
@@ -26,9 +26,9 @@ void main() {
List arr = [12836, "小哈"];
int hashArr = arr.hashCode;
print("Hash value of array $arr: $hashArr");
print("Array $arr has hash value $hashArr");
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode;
print("Hash value of node object $obj: $hashObj");
print("Node object $obj has hash value $hashObj");
}

View File

@@ -36,6 +36,5 @@ void main() {
print("\nTraverse keys only: Key");
map.keys.forEach((key) => print(key));
print("\nTraverse values only: Value");
map.forEach((key, value) => print("$value"));
map.values.forEach((value) => print(value));
}

View File

@@ -105,6 +105,6 @@ void main() {
for (int i = 0; i < 10; i++) {
queue.push(i);
queue.pop();
print("Round $i: after enqueue + dequeue, queue = ${queue.toArray()}");
print("After round $i of enqueue + dequeue, queue = ${queue.toArray()}");
}
}

View File

@@ -28,10 +28,10 @@ void main() {
// Insert node p between n1 and n2
n1.left = p;
p.left = n2;
print("\nAfter inserting node p:\n");
print("\nAfter inserting node P:\n");
printTree(n1);
// Remove node p
// Remove node P
n1.left = n2;
print("\nAfter removing node p:\n");
print("\nAfter removing node P:\n");
printTree(n1);
}

View File

@@ -40,7 +40,7 @@ func TestLinkedList(t *testing.T) {
/* Access a node */
node := access(n0, 3)
fmt.Println("Node at index 3 in the linked list =", node)
fmt.Println("Value of the node at index 3 in the linked list =", node)
/* Find a node */
index := findNode(n0, 2)

View File

@@ -8,14 +8,14 @@ package chapter_heap
// Implementing heap.Interface also requires implementing sort.Interface
type intHeap []any
// Push implements heap.Interface by appending an element for the heap package
// Push is a heap.Interface function that pushes an element onto the heap
func (h *intHeap) Push(x any) {
// Push and Pop use pointer receivers
// because they modify the slice length as well as its contents.
*h = append(*h, x.(int))
}
// Pop implements heap.Interface by removing the last element, where heap.Pop has moved the top element
// Pop is a heap.Interface function that pops the top element from the heap
func (h *intHeap) Pop() any {
// The element to remove is stored at the end
last := (*h)[len(*h)-1]

View File

@@ -14,14 +14,14 @@ import (
)
func testPush(h *intHeap, val int) {
// Call heap.Push, which uses heap.Interface to add an element
// Call a heap.Interface function to add an element
heap.Push(h, val)
fmt.Printf("\nAfter pushing %d onto the heap: \n", val)
PrintHeap(*h)
}
func testPop(h *intHeap) {
// Call heap.Pop, which uses heap.Interface to remove the top element
// Call a heap.Interface function to remove an element
val := heap.Pop(h)
fmt.Printf("\nAfter popping the top element %d from the heap: \n", val)
PrintHeap(*h)
@@ -91,8 +91,6 @@ func TestMyHeap(t *testing.T) {
}
func TestTopKHeap(t *testing.T) {
/* Initialize the heap */
// Prepare the input for heap-based top-k selection
nums := []int{1, 7, 6, 3, 2}
k := 3
res := topKHeap(nums, k)

View File

@@ -51,7 +51,6 @@ func TestDeque(t *testing.T) {
func TestArrayDeque(t *testing.T) {
/* Initialize the deque */
// Use the custom circular-array deque implementation
deque := newArrayDeque(16)
/* Enqueue elements */

View File

@@ -47,7 +47,7 @@ func TestQueue(t *testing.T) {
func TestArrayQueue(t *testing.T) {
// Initialize the queue and use its standard queue operations
// Initialize the queue and use the common queue interface
capacity := 10
queue := newArrayQueue(capacity)
if queue.pop() != nil {
@@ -84,7 +84,7 @@ func TestArrayQueue(t *testing.T) {
for i := 0; i < 10; i++ {
queue.push(i)
queue.pop()
fmt.Print("Round #", i, ": after enqueue + dequeue, queue =")
fmt.Print("After round ", i, " of enqueue + dequeue, queue =")
PrintSlice(queue.toSlice())
}
}

View File

@@ -45,7 +45,7 @@ func TestStack(t *testing.T) {
}
func TestArrayStack(t *testing.T) {
// Initialize the stack for use through its stack operations
// Initialize the stack and assign it to an interface
stack := newArrayStack()
// Push elements onto the stack

View File

@@ -32,10 +32,10 @@ func TestBinaryTree(t *testing.T) {
p := NewTreeNode(0)
n1.Left = p
p.Left = n2
fmt.Println("After inserting node p")
fmt.Println("After inserting node P")
PrintTree(n1)
// Remove a node
n1.Left = n2
fmt.Println("After removing node p")
fmt.Println("After removing node P")
PrintTree(n1)
}

View File

@@ -11,7 +11,7 @@ import java.util.*;
public class list {
public static void main(String[] args) {
/* Initialize the list */
// Use Integer[]: Integer is the wrapper type for int
// Note that the array type must be Integer[] rather than int[], because list elements must use Integer, the wrapper class for int
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
System.out.println("List nums = " + nums);

View File

@@ -21,7 +21,7 @@ public class built_in_hash {
double dec = 3.14159;
int hashDec = Double.hashCode(dec);
System.out.println("Decimal " + dec + " has hash value " + hashDec);
System.out.println("Floating-point number " + dec + " has hash value " + hashDec);
String str = "Hello 算法";
int hashStr = str.hashCode();

View File

@@ -109,7 +109,7 @@ public class array_queue {
for (int i = 0; i < 10; i++) {
queue.push(i);
queue.pop();
System.out.println("Round " + i + " : after enqueue + dequeue, queue = " + Arrays.toString(queue.toArray()));
System.out.println("After round " + i + " of enqueue + dequeue, queue = " + Arrays.toString(queue.toArray()));
}
}
}

View File

@@ -102,5 +102,5 @@ console.log('Is the queue empty = ' + isEmpty);
for (let i = 0; i < 10; i++) {
queue.push(i);
queue.pop();
console.log('Round ' + i + ' : after enqueue + dequeue, queue =', queue.toArray());
console.log('After round ' + i + ' of enqueue + dequeue, queue =', queue.toArray());
}

View File

@@ -9,7 +9,7 @@ package chapter_array_and_linkedlist
import utils.ListNode
import utils.printLinkedList
/* Insert node p after node n0 in the linked list */
/* Insert node P after node n0 in the linked list */
fun insert(n0: ListNode?, p: ListNode?) {
val n1 = n0?.next
p?.next = n1

View File

@@ -105,6 +105,6 @@ fun main() {
for (i in 0..9) {
queue.push(i)
queue.pop()
println("After enqueue and dequeue round $i: queue = ${queue.toArray().contentToString()}")
println("After round $i of enqueue + dequeue, queue = ${queue.toArray().contentToString()}")
}
}

View File

@@ -14,15 +14,15 @@ from modules import ListNode
if __name__ == "__main__":
num = 3
hash_num = hash(num)
print(f"Hash value of integer {num}: {hash_num}")
print(f"Integer {num} has hash value {hash_num}")
bol = True
hash_bol = hash(bol)
print(f"Hash value of Boolean {bol}: {hash_bol}")
print(f"Boolean {bol} has hash value {hash_bol}")
dec = 3.14159
hash_dec = hash(dec)
print(f"Hash value of floating-point number {dec}: {hash_dec}")
print(f"Floating-point number {dec} has hash value {hash_dec}")
str = "Hello 算法"
hash_str = hash(str)
@@ -30,8 +30,8 @@ if __name__ == "__main__":
tup = (12836, "小哈")
hash_tup = hash(tup)
print(f"Hash of the hash value of tuple {tup}: {hash(hash_tup)}")
print(f"Tuple {tup} has hash value {hash_tup}")
obj = ListNode(0)
hash_obj = hash(obj)
print(f"Hash value of node object {obj}: {hash_obj}")
print(f"Node object {obj} has hash value {hash_obj}")

View File

@@ -95,4 +95,4 @@ if __name__ == "__main__":
for i in range(10):
queue.push(i)
queue.pop()
print("Round", i, ": after enqueue + dequeue, queue = ", queue.to_list())
print("After round", i, "of enqueue + dequeue, queue = ", queue.to_list())

View File

@@ -17,7 +17,7 @@ if __name__ == "__main__":
deq.append(4)
deq.appendleft(3) # Add to the front
deq.appendleft(1)
print("Deque deq =", deq)
print("Deque deque =", deq)
# Access an element
front: int = deq[0] # Front element
@@ -28,10 +28,10 @@ if __name__ == "__main__":
# Dequeue an element
pop_front: int = deq.popleft() # Dequeue the front element
print("Element dequeued from the front, pop_front =", pop_front)
print("After dequeuing from the front, deq =", deq)
print("After dequeuing from the front, deque =", deq)
pop_rear: int = deq.pop() # Dequeue the rear element
print("Element dequeued from the rear, pop_rear =", pop_rear)
print("After dequeuing from the rear, deq =", deq)
print("After dequeuing from the rear, deque =", deq)
# Get the deque size
size: int = len(deq)

View File

@@ -10,25 +10,25 @@ require_relative '../utils/list_node'
if __FILE__ == $0
num = 3
hash_num = num.hash
puts "Hash value of integer #{num}: #{hash_num}"
puts "Integer #{num} has hash value #{hash_num}"
bol = true
hash_bol = bol.hash
puts "Hash value of Boolean #{bol}: #{hash_bol}"
puts "Boolean #{bol} has hash value #{hash_bol}"
dec = 3.14159
hash_dec = dec.hash
puts "Hash value of floating-point number #{dec}: #{hash_dec}"
puts "Floating-point number #{dec} has hash value #{hash_dec}"
str = "Hello 算法"
hash_str = str.hash
puts "Hash value of string #{str}: #{hash_str}"
tup = [12836, '小哈']
hash_tup = tup.hash
puts "Hash value of array #{tup}: #{hash_tup}"
arr = [12836, '小哈']
hash_arr = arr.hash
puts "Array #{arr} has hash value #{hash_arr}"
obj = ListNode.new(0)
hash_obj = obj.hash
puts "Hash value of node object #{obj}: #{hash_obj}"
puts "Node object #{obj} has hash value #{hash_obj}"
end

View File

@@ -102,6 +102,6 @@ if __FILE__ == $0
for i in 0...10
queue.push(i)
queue.pop
puts "After enqueueing and dequeueing in round #{i}, queue = #{queue.to_array}"
puts "After round #{i} of enqueue + dequeue, queue = #{queue.to_array}"
end
end

View File

@@ -14,7 +14,7 @@ if __FILE__ == $0
deque << 2
deque << 5
deque << 4
# Front insertion in a simple array takes O(n); Ruby implementations can optimize Array#unshift
# Note that Array#unshift has O(n) time complexity because the underlying structure is an array
deque.unshift(3)
deque.unshift(1)
puts "Deque deque = #{deque}"
@@ -26,7 +26,7 @@ if __FILE__ == $0
puts "Rear element peek_last = #{peek_last}"
# Dequeue an element
# Front removal in a simple array takes O(n); Ruby implementations can optimize Array#shift
# Note that Array#shift has O(n) time complexity because the underlying structure is an array
pop_front = deque.shift
puts "Element dequeued from the front: pop_front = #{pop_front}; deque = #{deque}"
pop_back = deque.pop

View File

@@ -4,7 +4,7 @@ Created Time: 2024-04-06
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### Doubly linked list node
### Doubly linked list node ###
class ListNode
attr_accessor :val
attr_accessor :next # Reference to the next node

View File

@@ -84,11 +84,11 @@ if __FILE__ == $0
# Access the front element
peek = queue.peek
puts "Front element peek = #{peek}"
puts "Front element front = #{peek}"
# Dequeue an element
pop_front = queue.pop
puts "Dequeued element pop_front = #{pop_front}"
puts "Dequeued element pop = #{pop_front}"
puts "After dequeueing, queue = #{queue.to_array}"
# Get the queue size

View File

@@ -23,7 +23,7 @@ if __FILE__ == $0
puts "Front element peek = #{peek}"
# Dequeue an element
# Front removal in a simple array takes O(n); Ruby implementations can optimize Array#shift
# Note that Array#shift has O(n) time complexity because the underlying structure is an array
pop = queue.shift
puts "Dequeued element pop = #{pop}"
puts "After dequeueing, queue = #{queue}"

View File

@@ -15,19 +15,19 @@ fn main() {
let mut num_hasher = DefaultHasher::new();
num.hash(&mut num_hasher);
let hash_num = num_hasher.finish();
println!("Hash of integer {}: {}", num, hash_num);
println!("Integer {} has hash value {}", num, hash_num);
let bol = true;
let mut bol_hasher = DefaultHasher::new();
bol.hash(&mut bol_hasher);
let hash_bol = bol_hasher.finish();
println!("Hash of boolean {}: {}", bol, hash_bol);
println!("Boolean {} has hash value {}", bol, hash_bol);
let dec: f32 = 3.14159;
let mut dec_hasher = DefaultHasher::new();
dec.to_bits().hash(&mut dec_hasher);
let hash_dec = dec_hasher.finish();
println!("Hash of the bit representation of floating-point value {}: {}", dec, hash_dec);
println!("Floating-point number {} has hash value {}", dec, hash_dec);
let str = "Hello 算法";
let mut str_hasher = DefaultHasher::new();
@@ -39,11 +39,11 @@ fn main() {
let mut tup_hasher = DefaultHasher::new();
arr.hash(&mut tup_hasher);
let hash_tup = tup_hasher.finish();
println!("Hash of tuple {:?}: {}", arr, hash_tup);
println!("Tuple {:?} has hash value {}", arr, hash_tup);
let node = ListNode::new(42);
let mut hasher = DefaultHasher::new();
node.borrow().val.hash(&mut hasher);
let hash = hasher.finish();
println!("Hash of the value in node {:?}: {}", node, hash);
println!("Node object {:?} has hash value {}", node, hash);
}

View File

@@ -120,6 +120,6 @@ fn main() {
for i in 0..10 {
queue.push(i);
queue.pop();
println!("After enqueueing and dequeueing in round {:?}, queue = {:?}", i, queue.to_vector());
println!("After round {:?} of enqueue + dequeue, queue = {:?}", i, queue.to_vector());
}
}

View File

@@ -19,9 +19,9 @@ pub fn main() {
// Access an element
let peek_first = deque.front().unwrap();
print!("\nFront element peek_first = {peek_first}");
print!("\nFront element peekFirst = {peek_first}");
let peek_last = deque.back().unwrap();
print!("\nRear element peek_last = {peek_last}");
print!("\nRear element peekLast = {peek_last}");
/* Enqueue elements */
deque.push_back(4);

View File

@@ -25,14 +25,14 @@ fn main() {
// Insert and remove nodes
let p = TreeNode::new(0);
// Insert node p between n1 and n2 in n1 -> n2
// Insert node P between n1 and n2 in n1 -> n2
p.borrow_mut().left = Some(Rc::clone(&n2));
n1.borrow_mut().left = Some(Rc::clone(&p));
println!("\nAfter inserting node p:\n");
println!("\nAfter inserting node P:\n");
print_util::print_tree(&n1);
// Remove node p
// Remove node P
drop(p);
n1.borrow_mut().left = Some(Rc::clone(&n2));
println!("\nAfter removing node p:\n");
println!("\nAfter removing node P:\n");
print_util::print_tree(&n1);
}

View File

@@ -1,90 +1,89 @@
<!-- [snippet]{init_array} -->
```python title="array.py"
# Initialize arrays
# Initialize the array
arr: list[int] = [0] * 5 # [ 0, 0, 0, 0, 0 ]
nums: list[int] = [1, 3, 2, 5, 4]
```
```cpp title="array.cpp"
/* Initialize arrays */
/* Initialize the array */
// Stored on the stack
int arr[5] = {};
int nums[5] = { 1, 3, 2, 5, 4 };
int nums[5] = {1, 3, 2, 5, 4};
// Stored on the heap (memory must be freed manually)
int* arr1 = new int[5] {};
int* nums1 = new int[5] { 1, 3, 2, 5, 4 };
int *arr1 = new int[5]{};
int *nums1 = new int[5]{1, 3, 2, 5, 4};
```
```java title="array.java"
/* Initialize arrays */
/* Initialize the array */
int[] arr = new int[5]; // { 0, 0, 0, 0, 0 }
int[] nums = { 1, 3, 2, 5, 4 };
```
```csharp title="array.cs"
/* Initialize arrays */
// Initialize the array
int[] arr = new int[5]; // [ 0, 0, 0, 0, 0 ]
int[] nums = [1, 3, 2, 5, 4];
```
```go title="array.go"
/* Initialize arrays */
/* Initialize the array */
var arr [5]int
// In Go, [5]int is an array with a specified length; []int is a slice
// Go array lengths are determined at compile time and must be constants
// To make extend() easier to implement, we treat slices as arrays below
// In Go, a type with a specified length ([5]int) is an array; without a length ([]int), it is a slice
// Go array lengths are determined at compile time, so the length must be a constant
// To make the extend() function easier to implement, we treat slices as arrays below
nums := []int{1, 3, 2, 5, 4}
```
```swift title="array.swift"
/* Initialize arrays */
/* Initialize the array */
let arr = Array(repeating: 0, count: 5) // [0, 0, 0, 0, 0]
let nums = [1, 3, 2, 5, 4]
var nums = [1, 3, 2, 5, 4]
```
```javascript title="array.js"
/* Initialize arrays */
var arr = new Array(5).fill(0);
var nums = [1, 3, 2, 5, 4];
/* Initialize the array */
const arr = new Array(5).fill(0);
let nums = [1, 3, 2, 5, 4];
```
```typescript title="array.ts"
/* Initialize arrays */
let arr: number[] = new Array(5).fill(0);
/* Initialize the array */
const arr: number[] = new Array(5).fill(0);
let nums: number[] = [1, 3, 2, 5, 4];
```
```dart title="array.dart"
/* Initialize arrays */
List<int> arr = List.filled(5, 0); // [0, 0, 0, 0, 0]
/* Initialize the array */
var arr = List.filled(5, 0); // [0, 0, 0, 0, 0]
List<int> nums = [1, 3, 2, 5, 4];
```
```rust title="array.rs"
/* Initialize arrays */
/* Initialize the array */
let arr: [i32; 5] = [0; 5]; // [0, 0, 0, 0, 0]
let slice: &[i32] = &[0; 5];
// In Rust, [i32; 5] is an array with a specified length; &[i32] is a slice
// Rust array lengths are determined at compile time and must be constants
// Vector is Rust's usual dynamic array type
// To make extend() easier to implement, we treat a vector as an array below
// In Rust, [i32; 5] is an array type with a fixed length, whereas &[i32] is a reference to a slice
// Rust array lengths are determined at compile time, so their lengths must be constant expressions
// Vec is the type normally used for dynamic arrays in Rust
// To simplify the extend() method, the following examples use a vector to represent an array
let nums: Vec<i32> = vec![1, 3, 2, 5, 4];
```
```c title="array.c"
/* Initialize arrays */
int arr[5] = { 0 }; // { 0, 0, 0, 0, 0 }
int nums[5] = { 1, 3, 2, 5, 4 };
/* Initialize the array */
int arr[5] = {0}; // { 0, 0, 0, 0, 0 }
int nums[] = {1, 3, 2, 5, 4};
```
```kotlin title="array.kt"
/* Initialize arrays */
var arr = IntArray(5) // { 0, 0, 0, 0, 0 }
/* Initialize the array */
val arr = IntArray(5) // { 0, 0, 0, 0, 0 }
var nums = intArrayOf(1, 3, 2, 5, 4)
```
```ruby title="array.rb"
# Initialize arrays
# Initialize the array
arr = Array.new(5, 0)
nums = [1, 3, 2, 5, 4]
```

View File

@@ -2,48 +2,53 @@
```python title=""
class ListNode:
"""Linked list node class"""
def __init__(self, val: int):
self.val: int = val # Node value
self.next: ListNode | None = None # Reference to the next node
self.val: int = val # Node value
self.next: ListNode | None = None # Reference to the next node
```
```cpp title=""
/* Linked list node structure */
/* Linked list node */
struct ListNode {
int val; // Node value
ListNode *next; // Pointer to the next node
ListNode(int x) : val(x), next(nullptr) {} // Constructor
int val; // Node value
ListNode *next; // Pointer to the next node
ListNode(int x) : val(x), next(nullptr) {
}
};
```
```java title=""
/* Linked list node class */
class ListNode {
int val; // Node value
ListNode next; // Reference to the next node
ListNode(int x) { val = x; } // Constructor
/* Linked list node */
public class ListNode {
public int val; // Node value
public ListNode next; // Reference to the next node
public ListNode(int x) {
val = x;
}
}
```
```csharp title=""
/* Linked list node class */
class ListNode(int x) { // Constructor
public int val = x; // Node value
public ListNode? next; // Reference to the next node
/* Linked list node */
public class ListNode(int x) {
public int val = x; // Node value
public ListNode? next; // Reference to the next node
}
```
```go title=""
/* Linked list node structure */
// ListNode represents a linked list node.
type ListNode struct {
Val int // Node value
Next *ListNode // Pointer to the next node
}
// NewListNode constructor: create a new linked list
func NewListNode(val int) *ListNode {
// NewListNode constructs a linked list node.
func NewListNode(v int) *ListNode {
return &ListNode{
Val: val,
Val: v,
Next: nil,
}
}
@@ -62,44 +67,54 @@ class ListNode {
```
```javascript title=""
/* Linked list node class */
/* Linked list node */
class ListNode {
val; // Node value
next; // Reference (pointer) to the next node
constructor(val, next) {
this.val = (val === undefined ? 0 : val); // Node value
this.next = (next === undefined ? null : next); // Reference to the next node
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
```
```typescript title=""
/* Linked list node class */
/* Linked list node */
class ListNode {
val: number;
next: ListNode | null;
val: number; // Node value
next: ListNode | null; // Reference to the next node
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val; // Node value
this.next = next === undefined ? null : next; // Reference to the next node
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
```
```dart title=""
/* Linked list node class */
/* Linked list node */
class ListNode {
int val; // Node value
ListNode? next; // Reference to the next node
ListNode(this.val, [this.next]); // Constructor
}
```
```rust title=""
use std::rc::Rc;
use std::cell::RefCell;
/* Linked list node class */
use std::rc::Rc;
/* Linked list node */
#[derive(Debug)]
struct ListNode {
val: i32, // Node value
next: Option<Rc<RefCell<ListNode>>>, // Pointer to the next node
pub struct 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 }))
}
}
```
@@ -110,10 +125,10 @@ typedef struct ListNode {
struct ListNode *next; // Pointer to the next node
} ListNode;
/* Constructor */
/* Constructor: initialize a new node */
ListNode *newListNode(int val) {
ListNode *node;
node = (ListNode *) malloc(sizeof(ListNode));
node = (ListNode *)malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
return node;
@@ -121,16 +136,14 @@ ListNode *newListNode(int val) {
```
```kotlin title=""
/* Linked list node class */
// Constructor
class ListNode(x: Int) {
val _val: Int = x // Node value
/* Linked list node */
class ListNode(var _val: Int) {
var next: ListNode? = null // Reference to the next node
}
```
```ruby title=""
# Linked list node class
### Linked list node class ###
class ListNode
attr_accessor :val # Node value
attr_accessor :next # Reference to the next node
@@ -145,13 +158,13 @@ end
<!-- [snippet]{init_linked_list} -->
```python title="linked_list.py"
# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize the nodes
# Initialize the individual nodes
n0 = ListNode(1)
n1 = ListNode(3)
n2 = ListNode(2)
n3 = ListNode(5)
n4 = ListNode(4)
# Link the nodes with references
# Set up references between the nodes
n0.next = n1
n1.next = n2
n2.next = n3
@@ -160,13 +173,13 @@ n3.next = n4
```cpp title="linked_list.cpp"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
ListNode* n0 = new ListNode(1);
ListNode* n1 = new ListNode(3);
ListNode* n2 = new ListNode(2);
ListNode* n3 = new ListNode(5);
ListNode* n4 = new ListNode(4);
// Link the nodes with references
// Initialize the individual nodes
ListNode *n0 = new ListNode(1);
ListNode *n1 = new ListNode(3);
ListNode *n2 = new ListNode(2);
ListNode *n3 = new ListNode(5);
ListNode *n4 = new ListNode(4);
// Set up references between the nodes
n0->next = n1;
n1->next = n2;
n2->next = n3;
@@ -175,13 +188,13 @@ n3->next = n4;
```java title="linked_list.java"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
// Initialize the individual nodes
ListNode n0 = new ListNode(1);
ListNode n1 = new ListNode(3);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(5);
ListNode n4 = new ListNode(4);
// Link the nodes with references
// Set up references between the nodes
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -189,14 +202,14 @@ n3.next = n4;
```
```csharp title="linked_list.cs"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
// Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
// Initialize the individual nodes
ListNode n0 = new(1);
ListNode n1 = new(3);
ListNode n2 = new(2);
ListNode n3 = new(5);
ListNode n4 = new(4);
// Link the nodes with references
// Set up references between the nodes
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -205,13 +218,14 @@ n3.next = n4;
```go title="linked_list.go"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
// Initialize the individual nodes
n0 := NewListNode(1)
n1 := NewListNode(3)
n2 := NewListNode(2)
n3 := NewListNode(5)
n4 := NewListNode(4)
// Link the nodes with references
// Set up references between the nodes
n0.Next = n1
n1.Next = n2
n2.Next = n3
@@ -220,13 +234,13 @@ n3.Next = n4
```swift title="linked_list.swift"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
// Initialize the individual nodes
let n0 = ListNode(x: 1)
let n1 = ListNode(x: 3)
let n2 = ListNode(x: 2)
let n3 = ListNode(x: 5)
let n4 = ListNode(x: 4)
// Link the nodes with references
// Set up references between the nodes
n0.next = n1
n1.next = n2
n2.next = n3
@@ -235,13 +249,13 @@ n3.next = n4
```javascript title="linked_list.js"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
// Initialize the individual nodes
const n0 = new ListNode(1);
const n1 = new ListNode(3);
const n2 = new ListNode(2);
const n3 = new ListNode(5);
const n4 = new ListNode(4);
// Link the nodes with references
// Set up references between the nodes
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -250,13 +264,13 @@ n3.next = n4;
```typescript title="linked_list.ts"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
// Initialize the individual nodes
const n0 = new ListNode(1);
const n1 = new ListNode(3);
const n2 = new ListNode(2);
const n3 = new ListNode(5);
const n4 = new ListNode(4);
// Link the nodes with references
// Set up references between the nodes
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -264,14 +278,14 @@ n3.next = n4;
```
```dart title="linked_list.dart"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
// Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
// Initialize the individual nodes
ListNode n0 = ListNode(1);
ListNode n1 = ListNode(3);
ListNode n2 = ListNode(2);
ListNode n3 = ListNode(5);
ListNode n4 = ListNode(4);
// Link the nodes with references
// Set up references between the nodes
n0.next = n1;
n1.next = n2;
n2.next = n3;
@@ -280,14 +294,14 @@ n3.next = n4;
```rust title="linked_list.rs"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
let n0 = Rc::new(RefCell::new(ListNode { val: 1, next: None }));
let n1 = Rc::new(RefCell::new(ListNode { val: 3, next: None }));
let n2 = Rc::new(RefCell::new(ListNode { val: 2, next: None }));
let n3 = Rc::new(RefCell::new(ListNode { val: 5, next: None }));
let n4 = Rc::new(RefCell::new(ListNode { val: 4, next: None }));
// Initialize the individual nodes
let n0 = ListNode::new(1);
let n1 = ListNode::new(3);
let n2 = ListNode::new(2);
let n3 = ListNode::new(5);
let n4 = ListNode::new(4);
// Link the nodes with references
// Set up references between the nodes
n0.borrow_mut().next = Some(n1.clone());
n1.borrow_mut().next = Some(n2.clone());
n2.borrow_mut().next = Some(n3.clone());
@@ -296,13 +310,13 @@ n3.borrow_mut().next = Some(n4.clone());
```c title="linked_list.c"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
ListNode* n0 = newListNode(1);
ListNode* n1 = newListNode(3);
ListNode* n2 = newListNode(2);
ListNode* n3 = newListNode(5);
ListNode* n4 = newListNode(4);
// Link the nodes with references
// Initialize the individual nodes
ListNode *n0 = newListNode(1);
ListNode *n1 = newListNode(3);
ListNode *n2 = newListNode(2);
ListNode *n3 = newListNode(5);
ListNode *n4 = newListNode(4);
// Set up references between the nodes
n0->next = n1;
n1->next = n2;
n2->next = n3;
@@ -311,28 +325,29 @@ n3->next = n4;
```kotlin title="linked_list.kt"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
// Initialize the individual nodes
val n0 = ListNode(1)
val n1 = ListNode(3)
val n2 = ListNode(2)
val n3 = ListNode(5)
val n4 = ListNode(4)
// Link the nodes with references
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
// Set up references between the nodes
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
```
```ruby title="linked_list.rb"
# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize the nodes
# Initialize the individual nodes
n0 = ListNode.new(1)
n1 = ListNode.new(3)
n2 = ListNode.new(2)
n3 = ListNode.new(5)
n4 = ListNode.new(4)
# Link the nodes with references
# Set up references between the nodes
n0.next = n1
n1.next = n2
n2.next = n3
@@ -345,39 +360,46 @@ https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%2
<!-- [snippet]{doubly_list_node_class} -->
```python title=""
class ListNode:
"""Doubly linked list node class"""
"""Doubly linked list node"""
def __init__(self, val: int):
self.val: int = val # Node value
self.next: ListNode | None = None # Reference to the successor
self.prev: ListNode | None = None # Reference to the predecessor
"""Constructor"""
self.val: int = val # Node value
self.next: ListNode | None = None # Reference to the next node
self.prev: ListNode | None = None # Reference to the previous node
```
```cpp title=""
/* Doubly linked list node structure */
struct ListNode {
int val; // Node value
ListNode *next; // Pointer to the successor
ListNode *prev; // Pointer to the predecessor
ListNode(int x) : val(x), next(nullptr), prev(nullptr) {} // Constructor
/* Doubly linked list node */
struct DoublyListNode {
int val; // Node value
DoublyListNode *next; // Pointer to the next node
DoublyListNode *prev; // Pointer to the previous node
DoublyListNode(int val) : val(val), prev(nullptr), next(nullptr) {
}
};
```
```java title=""
/* Doubly linked list node class */
/* Doubly linked list node */
class ListNode {
int val; // Node value
ListNode next; // Reference to the successor
ListNode prev; // Reference to the predecessor
ListNode(int x) { val = x; } // Constructor
int val; // Node value
ListNode next; // Reference to the next node
ListNode prev; // Reference to the previous node
ListNode(int val) {
this.val = val;
prev = next = null;
}
}
```
```csharp title=""
/* Doubly linked list node class */
class ListNode(int x) { // Constructor
public int val = x; // Node value
public ListNode? next; // Reference to the successor
public ListNode? prev; // Reference to the predecessor
/* Doubly linked list node */
public class ListNode(int val) {
public int val = val; // Node value
public ListNode? next = null; // Reference to the next node
public ListNode? prev = null; // Reference to the previous node
}
```
@@ -400,117 +422,119 @@ func NewDoublyListNode(val int) *DoublyListNode {
```
```swift title=""
/* Doubly linked list node class */
/* Doubly linked list node */
class ListNode {
var val: Int // Node value
var next: ListNode? // Reference to the successor
var prev: ListNode? // Reference to the predecessor
var next: ListNode? // Reference to the next node
weak var prev: ListNode? // Reference to the previous node
init(x: Int) { // Constructor
val = x
init(val: Int) {
self.val = val
}
}
```
```javascript title=""
/* Doubly linked list node class */
/* Doubly linked list node */
class ListNode {
constructor(val, next, prev) {
this.val = val === undefined ? 0 : val; // Node value
this.next = next === undefined ? null : next; // Reference to the successor
this.prev = prev === undefined ? null : prev; // Reference to the predecessor
prev; // Reference (pointer) to the previous node
next; // Reference (pointer) to the next node
val; // Node value
constructor(val) {
this.val = val;
this.next = null;
this.prev = null;
}
}
```
```typescript title=""
/* Doubly linked list node class */
/* Doubly linked list node */
class ListNode {
val: number;
next: ListNode | null;
prev: ListNode | null;
constructor(val?: number, next?: ListNode | null, prev?: ListNode | null) {
this.val = val === undefined ? 0 : val; // Node value
this.next = next === undefined ? null : next; // Reference to the successor
this.prev = prev === undefined ? null : prev; // Reference to the predecessor
prev: ListNode | null; // Reference (pointer) to the previous node
next: ListNode | null; // Reference (pointer) to the next node
val: number; // Node value
constructor(val: number) {
this.val = val;
this.next = null;
this.prev = null;
}
}
```
```dart title=""
/* Doubly linked list node class */
/* Doubly linked list node */
class ListNode {
int val; // Node value
ListNode? next; // Reference to the successor
ListNode? prev; // Reference to the predecessor
ListNode(this.val, [this.next, this.prev]); // Constructor
int val; // Node value
ListNode? next; // Reference to the next node
ListNode? prev; // Reference to the previous node
ListNode(this.val, {this.next, this.prev});
}
```
```rust title=""
use std::rc::Rc;
use std::cell::RefCell;
use std::rc::Rc;
/* Doubly linked list node type */
#[derive(Debug)]
struct ListNode {
val: i32, // Node value
next: Option<Rc<RefCell<ListNode>>>, // Pointer to the successor
prev: Option<Rc<RefCell<ListNode>>>, // Pointer to the predecessor
/* Doubly linked list node */
pub struct ListNode<T> {
pub val: T, // Node value
pub next: Option<Rc<RefCell<ListNode<T>>>>, // Pointer to the next node
pub prev: Option<Rc<RefCell<ListNode<T>>>>, // Pointer to the previous node
}
/* Constructor */
impl ListNode {
fn new(val: i32) -> Self {
ListNode {
impl<T> ListNode<T> {
pub fn new(val: T) -> Rc<RefCell<ListNode<T>>> {
Rc::new(RefCell::new(ListNode {
val,
next: None,
prev: None,
}
}))
}
}
```
```c title=""
/* Doubly linked list node structure */
typedef struct ListNode {
int val; // Node value
struct ListNode *next; // Pointer to the successor
struct ListNode *prev; // Pointer to the predecessor
} ListNode;
/* Doubly linked list node */
typedef struct DoublyListNode {
int val; // Node value
struct DoublyListNode *next; // Pointer to the next node
struct DoublyListNode *prev; // Pointer to the previous node
} DoublyListNode;
/* Constructor */
ListNode *newListNode(int val) {
ListNode *node;
node = (ListNode *) malloc(sizeof(ListNode));
node->val = val;
node->next = NULL;
node->prev = NULL;
return node;
DoublyListNode *newDoublyListNode(int num) {
DoublyListNode *new = (DoublyListNode *)malloc(sizeof(DoublyListNode));
new->val = num;
new->next = NULL;
new->prev = NULL;
return new;
}
```
```kotlin title=""
/* Doubly linked list node class */
// Constructor
class ListNode(x: Int) {
val _val: Int = x // Node value
var next: ListNode? = null // Reference to the successor
var prev: ListNode? = null // Reference to the predecessor
/* Doubly linked list node */
class ListNode(
var _val: Int // The node value is stored in _val
) {
var next: ListNode? = null // Reference to the next node
var prev: ListNode? = null // Reference to the previous node
}
```
```ruby title=""
# Doubly linked list node class
### Doubly linked list node ###
class ListNode
attr_accessor :val # Node value
attr_accessor :next # Reference to the successor
attr_accessor :prev # Reference to the predecessor
attr_accessor :val # Node value
attr_accessor :next # Reference to the next node
attr_accessor :prev # Reference to the previous node
def initialize(val=0, next_node=nil, prev_node=nil)
### Constructor ###
def initialize(val)
@val = val
@next = next_node
@prev = prev_node
end
end
```

View File

@@ -1,83 +1,82 @@
<!-- [snippet]{init_list} -->
```python title="list.py"
# Initialize lists
# Initialize the list
# Without initial values
nums1: list[int] = []
empty_nums: list[int] = []
# With initial values
nums: list[int] = [1, 3, 2, 5, 4]
```
```cpp title="list.cpp"
/* Initialize lists */
// In C++, vector is the list type used for nums here
/* Initialize the list */
// Without initial values
vector<int> nums1;
vector<int> emptyNums;
// With initial values
vector<int> nums = { 1, 3, 2, 5, 4 };
vector<int> nums = {1, 3, 2, 5, 4};
```
```java title="list.java"
/* Initialize lists */
/* Initialize the list */
// Without initial values
List<Integer> nums1 = new ArrayList<>();
// With initial values (use Integer[], the boxed counterpart of int[])
List<Integer> emptyNums = new ArrayList<>();
// With initial values (note that the array type must be Integer[] rather than int[], because list elements must use Integer, the wrapper class for int)
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
```
```csharp title="list.cs"
/* Initialize lists */
/* Initialize the list */
// Without initial values
List<int> nums1 = [];
List<int> emptyNums = [];
// With initial values
int[] numbers = [1, 3, 2, 5, 4];
List<int> nums = [.. numbers];
```
```go title="list_test.go"
/* Initialize lists */
/* Initialize the list */
// Without initial values
nums1 := []int{}
emptyNums := []int{}
// With initial values
nums := []int{1, 3, 2, 5, 4}
```
```swift title="list.swift"
/* Initialize lists */
/* Initialize the list */
// Without initial values
let nums1: [Int] = []
let emptyNums: [Int] = []
// With initial values
var nums = [1, 3, 2, 5, 4]
```
```javascript title="list.js"
/* Initialize lists */
/* Initialize the list */
// Without initial values
const nums1 = [];
const emptyNums = [];
// With initial values
const nums = [1, 3, 2, 5, 4];
```
```typescript title="list.ts"
/* Initialize lists */
/* Initialize the list */
// Without initial values
const nums1: number[] = [];
const emptyNums: number[] = [];
// With initial values
const nums: number[] = [1, 3, 2, 5, 4];
```
```dart title="list.dart"
/* Initialize lists */
/* Initialize the list */
// Without initial values
List<int> nums1 = [];
List<int> emptyNums = [];
// With initial values
List<int> nums = [1, 3, 2, 5, 4];
```
```rust title="list.rs"
/* Initialize lists */
// Initialize the list
// Without initial values
let nums1: Vec<i32> = Vec::new();
let empty_nums: Vec<i32> = Vec::new();
// With initial values
let mut nums: Vec<i32> = vec![1, 3, 2, 5, 4];
```
@@ -87,64 +86,63 @@ let mut nums: Vec<i32> = vec![1, 3, 2, 5, 4];
```
```kotlin title="list.kt"
/* Initialize lists */
/* Initialize the list */
// Without initial values
var nums1 = listOf<Int>()
val emptyNums = mutableListOf<Int>()
// With initial values
var numbers = arrayOf(1, 3, 2, 5, 4)
var nums = numbers.toMutableList()
val nums = mutableListOf(1, 3, 2, 5, 4)
```
```ruby title="list.rb"
# Initialize lists
# Initialize the list
# Without initial values
nums1 = []
empty_nums = []
# With initial values
nums = [1, 3, 2, 5, 4]
```
<!-- [tutor]{init_list_tutor} -->
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20%23%20Without%20initial%20values%0A%20%20%20%20nums1%20%3D%20%5B%5D%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20%23%20Without%20initial%20values%0A%20%20%20%20empty_nums%20%3D%20%5B%5D%0A%20%20%20%20%23%20With%20initial%20values%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D&cumulative=false&curInstr=4&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
<!-- [snippet]{access_element} -->
```python title="list.py"
# Access an element
num: int = nums[1] # Access the element at index 1
x: int = nums[1] # Access the element at index 1
# Update an element
nums[1] = 0 # Set the element at index 1 to 0
nums[1] = 0 # Update the element at index 1 to 0
```
```cpp title="list.cpp"
/* Access an element */
int num = nums[1]; // Access the element at index 1
int num = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
nums[1] = 0; // Update the element at index 1 to 0
```
```java title="list.java"
/* Access an element */
int num = nums.get(1); // Access the element at index 1
int num = nums.get(1); // Access the element at index 1
/* Update an element */
nums.set(1, 0); // Set the element at index 1 to 0
nums.set(1, 0); // Update the element at index 1 to 0
```
```csharp title="list.cs"
/* Access an element */
int num = nums[1]; // Access the element at index 1
int num = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
nums[1] = 0; // Update the element at index 1 to 0
```
```go title="list_test.go"
/* Access an element */
num := nums[1] // Access the element at index 1
num := nums[1] // Access the element at index 1
/* Update an element */
nums[1] = 0 // Set the element at index 1 to 0
nums[1] = 0 // Update the element at index 1 to 0
```
```swift title="list.swift"
@@ -152,38 +150,39 @@ nums[1] = 0 // Set the element at index 1 to 0
let num = nums[1] // Access the element at index 1
/* Update an element */
nums[1] = 0 // Set the element at index 1 to 0
nums[1] = 0 // Update the element at index 1 to 0
```
```javascript title="list.js"
/* Access an element */
const num = nums[1]; // Access the element at index 1
const num = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
nums[1] = 0; // Update the element at index 1 to 0
```
```typescript title="list.ts"
/* Access an element */
const num: number = nums[1]; // Access the element at index 1
const num: number = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
nums[1] = 0; // Update the element at index 1 to 0
```
```dart title="list.dart"
/* Access an element */
int num = nums[1]; // Access the element at index 1
int _num = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
nums[1] = 0; // Update the element at index 1 to 0
```
```rust title="list.rs"
/* Access an element */
let num: i32 = nums[1]; // Access the element at index 1
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
// Access an element
let num = nums[1]; // Access the element at index 1
// Update an element
nums[1] = 0; // Update the element at index 1 to 0
```
```c title="list.c"
@@ -192,27 +191,29 @@ nums[1] = 0; // Set the element at index 1 to 0
```kotlin title="list.kt"
/* Access an element */
val num = nums[1] // Access the element at index 1
val num = nums[1] // Access the element at index 1
/* Update an element */
nums[1] = 0 // Set the element at index 1 to 0
nums[1] = 0 // Update the element at index 1 to 0
```
```ruby title="list.rb"
# Access an element
num = nums[1] # Access the element at index 1
# Update an element
nums[1] = 0 # Set the element at index 1 to 0
nums[1] = 0 # Update the element at index 1 to 0
```
<!-- [tutor]{access_element_tutor} -->
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20Access%20an%20element%0A%20%20%20%20num%20%3D%20nums%5B1%5D%20%20%23%20Access%20the%20element%20at%20index%201%0A%0A%20%20%20%20%23%20Update%20an%20element%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20Set%20the%20element%20at%20index%201%20to%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20lists%0A%20%20%20%20nums%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%0A%20%20%20%20%23%20Access%20an%20element%0A%20%20%20%20x%20%3D%20nums%5B1%5D%20%20%23%20Access%20the%20element%20at%20index%201%0A%0A%20%20%20%20%23%20Update%20an%20element%0A%20%20%20%20nums%5B1%5D%20%3D%200%20%20%20%20%23%20Set%20the%20element%20at%20index%201%20to%200&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
<!-- [snippet]{insert_remove_element} -->
```python title="list.py"
# Clear the list
nums.clear()
# Append elements
# Append an element at the end
nums.append(1)
nums.append(3)
nums.append(2)
@@ -220,17 +221,17 @@ nums.append(5)
nums.append(4)
# Insert an element in the middle
nums.insert(3, 6) # Insert 6 at index 3
nums.insert(3, 6) # Insert the number 6 at index 3
# Remove an element
nums.pop(3) # Remove the element at index 3
nums.pop(3) # Remove the element at index 3
```
```cpp title="list.cpp"
/* Clear the list */
nums.clear();
/* Append elements */
/* Append an element at the end */
nums.push_back(1);
nums.push_back(3);
nums.push_back(2);
@@ -238,17 +239,17 @@ nums.push_back(5);
nums.push_back(4);
/* Insert an element in the middle */
nums.insert(nums.begin() + 3, 6); // Insert 6 at index 3
nums.insert(nums.begin() + 3, 6); // Insert the number 6 at index 3
/* Remove an element */
nums.erase(nums.begin() + 3); // Remove the element at index 3
nums.erase(nums.begin() + 3); // Remove the element at index 3
```
```java title="list.java"
/* Clear the list */
nums.clear();
/* Append elements */
/* Append at the end */
nums.add(1);
nums.add(3);
nums.add(2);
@@ -256,17 +257,17 @@ nums.add(5);
nums.add(4);
/* Insert an element in the middle */
nums.add(3, 6); // Insert 6 at index 3
nums.add(3, 6); // Insert the number 6 at index 3
/* Remove an element */
nums.remove(3); // Remove the element at index 3
nums.remove(3); // Remove the element at index 3
```
```csharp title="list.cs"
/* Clear the list */
nums.Clear();
/* Append elements */
/* Append at the end */
nums.Add(1);
nums.Add(3);
nums.Add(2);
@@ -274,17 +275,17 @@ nums.Add(5);
nums.Add(4);
/* Insert an element in the middle */
nums.Insert(3, 6); // Insert 6 at index 3
nums.Insert(3, 6); // Insert the number 6 at index 3
/* Remove an element */
nums.RemoveAt(3); // Remove the element at index 3
nums.RemoveAt(3); // Remove the element at index 3
```
```go title="list_test.go"
/* Clear the list */
nums = nil
/* Append elements */
/* Append at the end */
nums = append(nums, 1)
nums = append(nums, 3)
nums = append(nums, 2)
@@ -292,7 +293,7 @@ nums = append(nums, 5)
nums = append(nums, 4)
/* Insert an element in the middle */
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert 6 at index 3
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert the number 6 at index 3
/* Remove an element */
nums = append(nums[:3], nums[4:]...) // Remove the element at index 3
@@ -302,7 +303,7 @@ nums = append(nums[:3], nums[4:]...) // Remove the element at index 3
/* Clear the list */
nums.removeAll()
/* Append elements */
/* Append at the end */
nums.append(1)
nums.append(3)
nums.append(2)
@@ -310,7 +311,7 @@ nums.append(5)
nums.append(4)
/* Insert an element in the middle */
nums.insert(6, at: 3) // Insert 6 at index 3
nums.insert(6, at: 3) // Insert the number 6 at index 3
/* Remove an element */
nums.remove(at: 3) // Remove the element at index 3
@@ -320,7 +321,7 @@ nums.remove(at: 3) // Remove the element at index 3
/* Clear the list */
nums.length = 0;
/* Append elements */
/* Append an element at the end */
nums.push(1);
nums.push(3);
nums.push(2);
@@ -328,17 +329,17 @@ nums.push(5);
nums.push(4);
/* Insert an element in the middle */
nums.splice(3, 0, 6); // Insert 6 at index 3
nums.splice(3, 0, 6); // Insert the number 6 at index 3
/* Remove an element */
nums.splice(3, 1); // Remove the element at index 3
nums.splice(3, 1); // Remove the element at index 3
```
```typescript title="list.ts"
/* Clear the list */
nums.length = 0;
/* Append elements */
/* Append an element at the end */
nums.push(1);
nums.push(3);
nums.push(2);
@@ -346,17 +347,17 @@ nums.push(5);
nums.push(4);
/* Insert an element in the middle */
nums.splice(3, 0, 6); // Insert 6 at index 3
nums.splice(3, 0, 6); // Insert the number 6 at index 3
/* Remove an element */
nums.splice(3, 1); // Remove the element at index 3
nums.splice(3, 1); // Remove the element at index 3
```
```dart title="list.dart"
/* Clear the list */
nums.clear();
/* Append elements */
/* Append an element at the end */
nums.add(1);
nums.add(3);
nums.add(2);
@@ -364,28 +365,28 @@ nums.add(5);
nums.add(4);
/* Insert an element in the middle */
nums.insert(3, 6); // Insert 6 at index 3
nums.insert(3, 6); // Insert the number 6 at index 3
/* Remove an element */
nums.removeAt(3); // Remove the element at index 3
```
```rust title="list.rs"
/* Clear the list */
// Clear the list
nums.clear();
/* Append elements */
// Append an element at the end
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
/* Insert an element in the middle */
nums.insert(3, 6); // Insert 6 at index 3
// Insert an element in the middle
nums.insert(3, 6); // Insert the number 6 at index 3
/* Remove an element */
nums.remove(3); // Remove the element at index 3
// Remove an element
nums.remove(3); // Remove the element at index 3
```
```c title="list.c"
@@ -394,27 +395,27 @@ nums.remove(3); // Remove the element at index 3
```kotlin title="list.kt"
/* Clear the list */
nums.clear();
nums.clear()
/* Append elements */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
/* Append at the end */
nums.add(1)
nums.add(3)
nums.add(2)
nums.add(5)
nums.add(4)
/* Insert an element in the middle */
nums.add(3, 6); // Insert 6 at index 3
nums.add(3, 6) // Insert the number 6 at index 3
/* Remove an element */
nums.removeAt(3); // Remove the element at index 3
nums.removeAt(3) // Remove the element at index 3
```
```ruby title="list.rb"
# Clear the list
nums.clear
# Append elements
# Append an element at the end
nums << 1
nums << 3
nums << 2
@@ -422,7 +423,7 @@ nums << 5
nums << 4
# Insert an element in the middle
nums.insert(3, 6) # Insert 6 at index 3
nums.insert(3, 6) # Insert the number 6 at index 3
# Remove an element
nums.delete_at(3) # Remove the element at index 3
@@ -438,7 +439,7 @@ count = 0
for i in range(len(nums)):
count += nums[i]
# Traverse list elements directly
# Iterate directly over the list elements
for num in nums:
count += num
```
@@ -450,10 +451,10 @@ for (int i = 0; i < nums.size(); i++) {
count += nums[i];
}
/* Traverse list elements directly */
/* Iterate directly over the list elements */
count = 0;
for (int num : nums) {
count += num;
for (int x : nums) {
count += x;
}
```
@@ -464,9 +465,9 @@ for (int i = 0; i < nums.size(); i++) {
count += nums.get(i);
}
/* Traverse list elements directly */
for (int num : nums) {
count += num;
/* Iterate directly over the list elements */
for (int x : nums) {
count += x;
}
```
@@ -477,10 +478,10 @@ for (int i = 0; i < nums.Count; i++) {
count += nums[i];
}
/* Traverse list elements directly */
/* Iterate directly over the list elements */
count = 0;
foreach (int num in nums) {
count += num;
foreach (int x in nums) {
count += x;
}
```
@@ -491,10 +492,10 @@ for i := 0; i < len(nums); i++ {
count += nums[i]
}
/* Traverse list elements directly */
/* Iterate directly over the list elements */
count = 0
for _, num := range nums {
count += num
for _, x := range nums {
count += x
}
```
@@ -505,10 +506,10 @@ for i in nums.indices {
count += nums[i]
}
/* Traverse list elements directly */
/* Iterate directly over the list elements */
count = 0
for num in nums {
count += num
for x in nums {
count += x
}
```
@@ -519,10 +520,10 @@ for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* Traverse list elements directly */
/* Iterate directly over the list elements */
count = 0;
for (const num of nums) {
count += num;
for (const x of nums) {
count += x;
}
```
@@ -533,10 +534,10 @@ for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* Traverse list elements directly */
/* Iterate directly over the list elements */
count = 0;
for (const num of nums) {
count += num;
for (const x of nums) {
count += x;
}
```
@@ -544,13 +545,13 @@ for (const num of nums) {
/* Traverse the list by index */
int count = 0;
for (var i = 0; i < nums.length; i++) {
count += nums[i];
count += nums[i];
}
/* Traverse list elements directly */
/* Iterate directly over the list elements */
count = 0;
for (var num in nums) {
count += num;
for (var x in nums) {
count += x;
}
```
@@ -561,10 +562,10 @@ for i in 0..nums.len() {
_count += nums[i];
}
// Traverse list elements directly
// Iterate directly over the list elements
_count = 0;
for num in &nums {
_count += num;
for x in &nums {
_count += x;
}
```
@@ -579,9 +580,9 @@ for (i in nums.indices) {
count += nums[i]
}
/* Traverse list elements directly */
for (num in nums) {
count += num
/* Iterate directly over the list elements */
for (j in nums) {
count += j
}
```
@@ -589,13 +590,13 @@ for (num in nums) {
# Traverse the list by index
count = 0
for i in 0...nums.length
count += nums[i]
count += nums[i]
end
# Traverse list elements directly
# Iterate directly over the list elements
count = 0
for num in nums
count += num
nums.each do |x|
count += x
end
```
@@ -605,63 +606,63 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{concat_list} -->
```python title="list.py"
# Concatenate two lists
nums1: list[int] = [6, 8, 7, 10, 9]
nums += nums1 # Append nums1 to nums
nums1 = [6, 8, 7, 10, 9]
nums += nums1 # Append list nums1 to nums
```
```cpp title="list.cpp"
/* Concatenate two lists */
vector<int> nums1 = { 6, 8, 7, 10, 9 };
// Append nums1 to nums
vector<int> nums1 = {6, 8, 7, 10, 9};
// Append list nums1 to nums
nums.insert(nums.end(), nums1.begin(), nums1.end());
```
```java title="list.java"
/* Concatenate two lists */
List<Integer> nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 }));
nums.addAll(nums1); // Append nums1 to nums
nums.addAll(nums1); // Append list nums1 to nums
```
```csharp title="list.cs"
/* Concatenate two lists */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1); // Append nums1 to nums
nums.AddRange(nums1); // Append list nums1 to nums
```
```go title="list_test.go"
/* Concatenate two lists */
nums1 := []int{6, 8, 7, 10, 9}
nums = append(nums, nums1...) // Append nums1 to nums
nums = append(nums, nums1...) // Append list nums1 to nums
```
```swift title="list.swift"
/* Concatenate two lists */
let nums1 = [6, 8, 7, 10, 9]
nums.append(contentsOf: nums1) // Append nums1 to nums
nums.append(contentsOf: nums1) // Append list nums1 to nums
```
```javascript title="list.js"
/* Concatenate two lists */
const nums1 = [6, 8, 7, 10, 9];
nums.push(...nums1); // Append nums1 to nums
nums.push(...nums1); // Append list nums1 to nums
```
```typescript title="list.ts"
/* Concatenate two lists */
const nums1: number[] = [6, 8, 7, 10, 9];
nums.push(...nums1); // Append nums1 to nums
nums.push(...nums1); // Append list nums1 to nums
```
```dart title="list.dart"
/* Concatenate two lists */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.addAll(nums1); // Append nums1 to nums
nums.addAll(nums1); // Append list nums1 to nums
```
```rust title="list.rs"
/* Concatenate two lists */
let nums1: Vec<i32> = vec![6, 8, 7, 10, 9];
nums.extend(nums1);
// Concatenate two lists
let mut nums1 = vec![6, 8, 7, 10, 9];
nums.append(&mut nums1); // append moves the elements out of nums1, leaving nums1 empty
```
```c title="list.c"
@@ -670,8 +671,8 @@ nums.extend(nums1);
```kotlin title="list.kt"
/* Concatenate two lists */
val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList()
nums.addAll(nums1) // Append nums1 to nums
val nums1 = mutableListOf(6, 8, 7, 10, 9)
nums.addAll(nums1) // Append list nums1 to nums
```
```ruby title="list.rb"
@@ -686,52 +687,52 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{sort_list} -->
```python title="list.py"
# Sort the list
nums.sort() # After sorting, elements are in ascending order
nums.sort() # After sorting, the list elements are in ascending order
```
```cpp title="list.cpp"
/* Sort the list */
sort(nums.begin(), nums.end()); // After sorting, elements are in ascending order
sort(nums.begin(), nums.end()); // After sorting, the list elements are in ascending order
```
```java title="list.java"
/* Sort the list */
Collections.sort(nums); // After sorting, elements are in ascending order
Collections.sort(nums); // After sorting, the list elements are in ascending order
```
```csharp title="list.cs"
/* Sort the list */
nums.Sort(); // After sorting, elements are in ascending order
nums.Sort(); // After sorting, the list elements are in ascending order
```
```go title="list_test.go"
/* Sort the list */
sort.Ints(nums) // After sorting, elements are in ascending order
sort.Ints(nums) // After sorting, the list elements are in ascending order
```
```swift title="list.swift"
/* Sort the list */
nums.sort() // After sorting, elements are in ascending order
nums.sort() // After sorting, the list elements are in ascending order
```
```javascript title="list.js"
/* Sort the list */
nums.sort((a, b) => a - b); // After sorting, elements are in ascending order
nums.sort((a, b) => a - b); // After sorting, the list elements are in ascending order
```
```typescript title="list.ts"
/* Sort the list */
nums.sort((a, b) => a - b); // After sorting, elements are in ascending order
nums.sort((a, b) => a - b); // After sorting, the list elements are in ascending order
```
```dart title="list.dart"
/* Sort the list */
nums.sort(); // After sorting, elements are in ascending order
nums.sort(); // After sorting, the list elements are in ascending order
```
```rust title="list.rs"
/* Sort the list */
nums.sort(); // After sorting, elements are in ascending order
// Sort the list
nums.sort(); // After sorting, the list elements are in ascending order
```
```c title="list.c"
@@ -740,12 +741,12 @@ nums.sort(); // After sorting, elements are in ascending order
```kotlin title="list.kt"
/* Sort the list */
nums.sort() // After sorting, elements are in ascending order
nums.sort() // After sorting, the list elements are in ascending order
```
```ruby title="list.rb"
# Sort the list
nums = nums.sort { |a, b| a <=> b } # After sorting, elements are in ascending order
nums = nums.sort { |a, b| a <=> b } # After sorting, the list elements are in ascending order
```
<!-- [tutor]{sort_list_tutor} -->

View File

@@ -2,100 +2,122 @@
```python title="built_in_hash.py"
num = 3
hash_num = hash(num)
# The hash of the integer 3 is 3
print(f"Integer {num} has hash value {hash_num}")
# Integer 3 has hash value 3
bol = True
hash_bol = hash(bol)
# The hash of the Boolean True is 1
print(f"Boolean {bol} has hash value {hash_bol}")
# Boolean True has hash value 1
dec = 3.14159
hash_dec = hash(dec)
# The hash of the floating-point number 3.14159 is 326484311674566659
print(f"Floating-point number {dec} has hash value {hash_dec}")
# Floating-point number 3.14159 has hash value 326484311674566659
str = "Hello 算法"
hash_str = hash(str)
# The hash of the string “Hello 算法” is 4617003410720528961
print(f"String '{str}' has hash value {hash_str}")
# String 'Hello 算法' has hash value 4617003410720528961
tup = (12836, "小哈")
hash_tup = hash(tup)
# The hash of the tuple (12836, '小哈') is 1029005403108185979
print(f"Tuple {tup} has hash value {hash_tup}")
# Tuple (12836, '小哈') has hash value 1029005403108185979
obj = ListNode(0)
hash_obj = hash(obj)
# The hash of the node object <ListNode object at 0x1058fd810> is 274267521
print(f"Node object {obj} has hash value {hash_obj}")
# Node object <modules.list_node.ListNode object at 0x1058fd810> has hash value 274267521
```
```cpp title="built_in_hash.cpp"
int num = 3;
size_t hashNum = hash<int>()(num);
// The hash of the integer 3 is 3
cout << "Integer " << num << " has hash value " << hashNum << "\n";
// Integer 3 has hash value 3
bool bol = true;
size_t hashBol = hash<bool>()(bol);
// The hash of the Boolean 1 is 1
cout << "Boolean " << bol << " has hash value " << hashBol << "\n";
// Boolean 1 has hash value 1
double dec = 3.14159;
size_t hashDec = hash<double>()(dec);
// The hash of the floating-point number 3.14159 is 4614256650576692846
cout << "Floating-point number " << dec << " has hash value " << hashDec << "\n";
// Floating-point number 3.14159 has hash value 4614256650576692846
string str = "Hello 算法";
size_t hashStr = hash<string>()(str);
// The hash of the string “Hello 算法” is 15466937326284535026
cout << "String '" << str << "' has hash value " << hashStr << "\n";
// String 'Hello 算法' has hash value 15466937326284535026
// In C++, built-in std::hash() provides hashing only for basic data types
// Hashing for arrays and objects must be implemented separately
// In C++, the built-in std::hash() only computes hash values for basic data types
// Hashing arrays and objects requires a custom implementation
```
```java title="built_in_hash.java"
int num = 3;
int hashNum = Integer.hashCode(num);
// The hash of the integer 3 is 3
System.out.println("Integer " + num + " has hash value " + hashNum);
// Integer 3 has hash value 3
boolean bol = true;
int hashBol = Boolean.hashCode(bol);
// The hash of the Boolean true is 1231
System.out.println("Boolean " + bol + " has hash value " + hashBol);
// Boolean true has hash value 1231
double dec = 3.14159;
int hashDec = Double.hashCode(dec);
// The hash of the floating-point number 3.14159 is -1340954729
System.out.println("Floating-point number " + dec + " has hash value " + hashDec);
// Floating-point number 3.14159 has hash value -1340954729
String str = "Hello 算法";
int hashStr = str.hashCode();
// The hash of the string “Hello 算法” is -727081396
System.out.println("String '" + str + "' has hash value " + hashStr);
// String 'Hello 算法' has hash value -727081396
Object[] arr = { 12836, "小哈" };
int hashTup = Arrays.hashCode(arr);
// The hash of the array [12836, 小哈] is 1151158
int hashArr = Arrays.hashCode(arr);
System.out.println("Array " + Arrays.toString(arr) + " has hash value " + hashArr);
// Array [12836, 小哈] has hash value 1151158
ListNode obj = new ListNode(0);
int hashObj = obj.hashCode();
// The hash of the node object utils.ListNode@7dc5e7b4 is 2110121908
System.out.println("Node object " + obj + " has hash value " + hashObj);
// Node object utils.ListNode@7dc5e7b4 has hash value 2110121908
```
```csharp title="built_in_hash.cs"
int num = 3;
int hashNum = num.GetHashCode();
// The hash of the integer 3 is 3;
Console.WriteLine("Integer " + num + " has hash value " + hashNum);
// Integer 3 has hash value 3
bool bol = true;
int hashBol = bol.GetHashCode();
// The hash of the Boolean true is 1;
Console.WriteLine("Boolean " + bol + " has hash value " + hashBol);
// Boolean True has hash value 1
double dec = 3.14159;
int hashDec = dec.GetHashCode();
// The hash of the floating-point number 3.14159 is -1340954729;
Console.WriteLine("Floating-point number " + dec + " has hash value " + hashDec);
// Floating-point number 3.14159 has hash value -1340954729
string str = "Hello 算法";
int hashStr = str.GetHashCode();
// The hash of the string “Hello 算法” is -586107568;
Console.WriteLine("String '" + str + "' has hash value " + hashStr);
// String 'Hello 算法' has hash value -586107568
object[] arr = [12836, "小哈"];
int hashTup = arr.GetHashCode();
// The hash of the array [12836, 小哈] is 42931033;
int hashArr = arr.GetHashCode();
Console.WriteLine("Array [" + string.Join(", ", arr) + "] has hash value " + hashArr);
// Array [12836, 小哈] has hash value 42931033
ListNode obj = new(0);
int hashObj = obj.GetHashCode();
// The hash of the node object 0 is 39053774;
Console.WriteLine("Node object " + obj + " has hash value " + hashObj);
// Node object 0 has hash value 39053774
```
```go title="built_in_hash.go"
@@ -105,27 +127,33 @@ int hashObj = obj.GetHashCode();
```swift title="built_in_hash.swift"
let num = 3
let hashNum = num.hashValue
// The hash of the integer 3 is 9047044699613009734
print("Integer \(num) has hash value \(hashNum)")
// Integer 3 has hash value 9047044699613009734
let bol = true
let hashBol = bol.hashValue
// The hash of the Boolean true is -4431640247352757451
print("Boolean \(bol) has hash value \(hashBol)")
// Boolean true has hash value -4431640247352757451
let dec = 3.14159
let hashDec = dec.hashValue
// The hash of the floating-point number 3.14159 is -2465384235396674631
print("Floating-point number \(dec) has hash value \(hashDec)")
// Floating-point number 3.14159 has hash value -2465384235396674631
let str = "Hello 算法"
let hashStr = str.hashValue
// The hash of the string “Hello 算法” is -7850626797806988787
print("String '\(str)' has hash value \(hashStr)")
// String 'Hello 算法' has hash value -7850626797806988787
let arr = [AnyHashable(12836), AnyHashable("小哈")]
let hashTup = arr.hashValue
// The hash of the array [AnyHashable(12836), AnyHashable("小哈")] is -2308633508154532996
let hashArr = arr.hashValue
print("Array \(arr) has hash value \(hashArr)")
// Array [AnyHashable(12836), AnyHashable("小哈")] has hash value -2308633508154532996
let obj = ListNode(x: 0)
let hashObj = obj.hashValue
// The hash of the node object utils.ListNode is -2434780518035996159
print("Node object \(obj) has hash value \(hashObj)")
// Node object utils.ListNode has hash value -2434780518035996159
```
```javascript title="built_in_hash.js"
@@ -139,27 +167,33 @@ let hashObj = obj.hashValue
```dart title="built_in_hash.dart"
int num = 3;
int hashNum = num.hashCode;
// The hash of the integer 3 is 34803
print("Integer $num has hash value $hashNum");
// Integer 3 has hash value 34803
bool bol = true;
int hashBol = bol.hashCode;
// The hash of the Boolean true is 1231
print("Boolean $bol has hash value $hashBol");
// Boolean true has hash value 1231
double dec = 3.14159;
int hashDec = dec.hashCode;
// The hash of the floating-point number 3.14159 is 2570631074981783
print("Floating-point number $dec has hash value $hashDec");
// Floating-point number 3.14159 has hash value 2570631074981783
String str = "Hello 算法";
int hashStr = str.hashCode;
// The hash of the string “Hello 算法” is 468167534
print("String '$str' has hash value $hashStr");
// String 'Hello 算法' has hash value 468167534
List arr = [12836, "小哈"];
int hashArr = arr.hashCode;
// The hash of the array [12836, 小哈] is 976512528
print("Array $arr has hash value $hashArr");
// Array [12836, 小哈] has hash value 976512528
ListNode obj = new ListNode(0);
ListNode obj = ListNode(0);
int hashObj = obj.hashCode;
// The hash of the node object Instance of 'ListNode' is 1033450432
print("Node object $obj has hash value $hashObj");
// Node object Instance of 'ListNode' has hash value 1033450432
```
```rust title="built_in_hash.rs"
@@ -170,37 +204,43 @@ let num = 3;
let mut num_hasher = DefaultHasher::new();
num.hash(&mut num_hasher);
let hash_num = num_hasher.finish();
// The hash of the integer 3 is 568126464209439262
println!("Integer {} has hash value {}", num, hash_num);
// Integer 3 has hash value 568126464209439262
let bol = true;
let mut bol_hasher = DefaultHasher::new();
bol.hash(&mut bol_hasher);
let hash_bol = bol_hasher.finish();
// The hash of the Boolean true is 4952851536318644461
println!("Boolean {} has hash value {}", bol, hash_bol);
// Boolean true has hash value 4952851536318644461
let dec: f32 = 3.14159;
let mut dec_hasher = DefaultHasher::new();
dec.to_bits().hash(&mut dec_hasher);
let hash_dec = dec_hasher.finish();
// The hash of the floating-point number 3.14159 is 2566941990314602357
println!("Floating-point number {} has hash value {}", dec, hash_dec);
// Floating-point number 3.14159 has hash value 2566941990314602357
let str = "Hello 算法";
let mut str_hasher = DefaultHasher::new();
str.hash(&mut str_hasher);
let hash_str = str_hasher.finish();
// The hash of the string “Hello 算法” is 16092673739211250988
println!("String '{}' has hash value {}", str, hash_str);
// String 'Hello 算法' has hash value 16092673739211250988
let arr = (&12836, &"小哈");
let tup = (&12836, &"小哈");
let mut tup_hasher = DefaultHasher::new();
arr.hash(&mut tup_hasher);
tup.hash(&mut tup_hasher);
let hash_tup = tup_hasher.finish();
// The hash of the tuple (12836, "小哈") is 1885128010422702749
println!("Tuple {:?} has hash value {}", tup, hash_tup);
// Tuple (12836, "小哈") has hash value 1885128010422702749
let node = ListNode::new(42);
let mut hasher = DefaultHasher::new();
node.borrow().val.hash(&mut hasher);
let hash = hasher.finish();
// The hash of the node object RefCell { value: ListNode { val: 42, next: None } } is 15387811073369036852
let mut node_hasher = DefaultHasher::new();
node.borrow().val.hash(&mut node_hasher);
let hash_node = node_hasher.finish();
println!("Node object {:?} has hash value {}", node, hash_node);
// Node object RefCell { value: ListNode { val: 42, next: None } } has hash value 15387811073369036852
```
```c title="built_in_hash.c"
@@ -210,54 +250,66 @@ let hash = hasher.finish();
```kotlin title="built_in_hash.kt"
val num = 3
val hashNum = num.hashCode()
// The hash of the integer 3 is 3
println("Integer $num has hash value $hashNum")
// Integer 3 has hash value 3
val bol = true
val hashBol = bol.hashCode()
// The hash of the Boolean true is 1231
println("Boolean $bol has hash value $hashBol")
// Boolean true has hash value 1231
val dec = 3.14159
val hashDec = dec.hashCode()
// The hash of the floating-point number 3.14159 is -1340954729
println("Floating-point number $dec has hash value $hashDec")
// Floating-point number 3.14159 has hash value -1340954729
val str = "Hello 算法"
val hashStr = str.hashCode()
// The hash of the string “Hello 算法” is -727081396
println("String '$str' has hash value $hashStr")
// String 'Hello 算法' has hash value -727081396
val arr = arrayOf<Any>(12836, "小哈")
val hashTup = arr.hashCode()
// The hash of the array [12836, 小哈] is 189568618
val hashArr = arr.contentHashCode()
println("Array ${arr.contentToString()} has hash value $hashArr")
// Array [12836, 小哈] has hash value 1151158
val obj = ListNode(0)
val hashObj = obj.hashCode()
// The hash of the node object utils.ListNode@1d81eb93 is 495053715
println("Node object $obj has hash value $hashObj")
// Node object utils.ListNode@1d81eb93 has hash value 495053715
```
```ruby title="built_in_hash.rb"
num = 3
hash_num = num.hash
# The hash of the integer 3 is -4385856518450339636
puts "Integer #{num} has hash value #{hash_num}"
# Integer 3 has hash value -4385856518450339636
bol = true
hash_bol = bol.hash
# The hash of the Boolean true is -1617938112149317027
puts "Boolean #{bol} has hash value #{hash_bol}"
# Boolean true has hash value -1617938112149317027
dec = 3.14159
hash_dec = dec.hash
# The hash of the floating-point number 3.14159 is -1479186995943067893
puts "Floating-point number #{dec} has hash value #{hash_dec}"
# Floating-point number 3.14159 has hash value -1479186995943067893
str = "Hello 算法"
hash_str = str.hash
# The hash of the string “Hello 算法” is -4075943250025831763
puts "String '#{str}' has hash value #{hash_str}"
# String 'Hello 算法' has hash value -4075943250025831763
tup = [12836, '小哈']
hash_tup = tup.hash
# The hash of the tuple (12836, '小哈') is 1999544809202288822
arr = [12836, '小哈']
hash_arr = arr.hash
puts "Array #{arr} has hash value #{hash_arr}"
# Array [12836, "小哈"] has hash value 1999544809202288822
obj = ListNode.new(0)
hash_obj = obj.hash
# The hash of the node object #<ListNode:0x000078133140ab70> is 4302940560806366381
puts "Node object #{obj} has hash value #{hash_obj}"
# Node object #<ListNode:0x000078133140ab70> has hash value 4302940560806366381
```
<!-- [tutor]{builtin_hash_tutor} -->
https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked-list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20next%20node%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20integer%203%20is%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20Boolean%20True%20is%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20floating-point%20number%203.14159%20is%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20string%20%E2%80%9CHello%20%E7%AE%97%E6%B3%95%E2%80%9D%20is%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20tuple%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20is%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20%23%20The%20hash%20of%20the%20node%20object%20%3CListNode%20object%20at%200x1058fd810%3E%20is%20274267521&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=class%20ListNode%3A%0A%20%20%20%20%22%22%22Linked-list%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.next%3A%20ListNode%20%7C%20None%20%3D%20None%20%20%23%20Reference%20to%20the%20next%20node%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20num%20%3D%203%0A%20%20%20%20hash_num%20%3D%20hash%28num%29%0A%20%20%20%20print%28f%22Integer%20%7Bnum%7D%20has%20hash%20value%20%7Bhash_num%7D%22%29%0A%20%20%20%20%23%20Integer%203%20has%20hash%20value%203%0A%0A%20%20%20%20bol%20%3D%20True%0A%20%20%20%20hash_bol%20%3D%20hash%28bol%29%0A%20%20%20%20print%28f%22Boolean%20%7Bbol%7D%20has%20hash%20value%20%7Bhash_bol%7D%22%29%0A%20%20%20%20%23%20Boolean%20True%20has%20hash%20value%201%0A%0A%20%20%20%20dec%20%3D%203.14159%0A%20%20%20%20hash_dec%20%3D%20hash%28dec%29%0A%20%20%20%20print%28f%22Floating-point%20number%20%7Bdec%7D%20has%20hash%20value%20%7Bhash_dec%7D%22%29%0A%20%20%20%20%23%20Floating-point%20number%203.14159%20has%20hash%20value%20326484311674566659%0A%0A%20%20%20%20str%20%3D%20%22Hello%20%E7%AE%97%E6%B3%95%22%0A%20%20%20%20hash_str%20%3D%20hash%28str%29%0A%20%20%20%20print%28f%22String%20%27%7Bstr%7D%27%20has%20hash%20value%20%7Bhash_str%7D%22%29%0A%20%20%20%20%23%20String%20%27Hello%20%E7%AE%97%E6%B3%95%27%20has%20hash%20value%204617003410720528961%0A%0A%20%20%20%20tup%20%3D%20%2812836%2C%20%22%E5%B0%8F%E5%93%88%22%29%0A%20%20%20%20hash_tup%20%3D%20hash%28tup%29%0A%20%20%20%20print%28f%22Tuple%20%7Btup%7D%20has%20hash%20value%20%7Bhash_tup%7D%22%29%0A%20%20%20%20%23%20Tuple%20%2812836%2C%20%27%E5%B0%8F%E5%93%88%27%29%20has%20hash%20value%201029005403108185979%0A%0A%20%20%20%20obj%20%3D%20ListNode%280%29%0A%20%20%20%20hash_obj%20%3D%20hash%28obj%29%0A%20%20%20%20print%28f%22Node%20object%20%7Bobj%7D%20has%20hash%20value%20%7Bhash_obj%7D%22%29%0A%20%20%20%20%23%20Node%20object%20%3Cmodules.list_node.ListNode%20object%20at%200x1058fd810%3E%20has%20hash%20value%20274267521%0A&cumulative=false&curInstr=19&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false

View File

@@ -1,72 +1,72 @@
<!-- [snippet]{hash_map_operations} -->
```python title="hash_map.py"
# Initialize a hash table
hmap: dict = {}
# Initialize the hash table
hmap = dict[int, str]()
# Insertion
# Add key-value pairs (key, value) to the hash table
# Insert operation
# Insert the key-value pair (key, value) into the hash table
hmap[12836] = "小哈"
hmap[15937] = "小啰"
hmap[16750] = "小算"
hmap[13276] = "小法"
hmap[10583] = "小鸭"
# Lookup
# Lookup operation
# Look up key in the hash table to obtain value
name: str = hmap[15937]
# Deletion
# Remove a key-value pair (key, value) from the hash table
# Remove operation
# Remove the key-value pair (key, value) from the hash table
hmap.pop(10583)
```
```cpp title="hash_map.cpp"
/* Initialize a hash table */
/* Initialize the hash table */
unordered_map<int, string> map;
/* Insertion */
// Add key-value pairs (key, value) to the hash table
/* Insert operation */
// Insert the key-value pair (key, value) into the hash table
map[12836] = "小哈";
map[15937] = "小啰";
map[16750] = "小算";
map[13276] = "小法";
map[10583] = "小鸭";
/* Lookup */
/* Lookup operation */
// Look up key in the hash table to obtain value
string name = map[15937];
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
/* Remove operation */
// Remove the key-value pair (key, value) from the hash table
map.erase(10583);
```
```java title="hash_map.java"
/* Initialize a hash table */
/* Initialize the hash table */
Map<Integer, String> map = new HashMap<>();
/* Insertion */
// Add key-value pairs (key, value) to the hash table
/* Insert operation */
// Insert the key-value pair (key, value) into the hash table
map.put(12836, "小哈");
map.put(15937, "小啰");
map.put(16750, "小算");
map.put(13276, "小法");
map.put(10583, "小鸭");
/* Lookup */
/* Lookup operation */
// Look up key in the hash table to obtain value
String name = map.get(15937);
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
/* Remove operation */
// Remove the key-value pair (key, value) from the hash table
map.remove(10583);
```
```csharp title="hash_map.cs"
/* Initialize a hash table */
/* Initialize the hash table */
Dictionary<int, string> map = new() {
/* Insertion */
// Add key-value pairs (key, value) to the hash table
/* Insert operation */
// Insert the key-value pair (key, value) into the hash table
{ 12836, "小哈" },
{ 15937, "小啰" },
{ 16750, "小算" },
@@ -74,144 +74,141 @@ Dictionary<int, string> map = new() {
{ 10583, "小鸭" }
};
/* Lookup */
/* Lookup operation */
// Look up key in the hash table to obtain value
string name = map[15937];
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
/* Remove operation */
// Remove the key-value pair (key, value) from the hash table
map.Remove(10583);
```
```go title="hash_map_test.go"
/* Initialize a hash table */
/* Initialize the hash table */
hmap := make(map[int]string)
/* Insertion */
// Add key-value pairs (key, value) to the hash table
/* Insert operation */
// Insert the key-value pair (key, value) into the hash table
hmap[12836] = "小哈"
hmap[15937] = "小啰"
hmap[16750] = "小算"
hmap[13276] = "小法"
hmap[10583] = "小鸭"
/* Lookup */
/* Lookup operation */
// Look up key in the hash table to obtain value
name := hmap[15937]
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
/* Remove operation */
// Remove the key-value pair (key, value) from the hash table
delete(hmap, 10583)
```
```swift title="hash_map.swift"
/* Initialize a hash table */
/* Initialize the hash table */
var map: [Int: String] = [:]
/* Insertion */
// Add key-value pairs (key, value) to the hash table
/* Insert operation */
// Insert the key-value pair (key, value) into the hash table
map[12836] = "小哈"
map[15937] = "小啰"
map[16750] = "小算"
map[13276] = "小法"
map[10583] = "小鸭"
/* Lookup */
/* Lookup operation */
// Look up key in the hash table to obtain value
let name = map[15937]!
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
/* Remove operation */
// Remove the key-value pair (key, value) from the hash table
map.removeValue(forKey: 10583)
```
```javascript title="hash_map.js"
/* Initialize a hash table */
/* Initialize the hash table */
const map = new Map();
/* Insertion */
// Add key-value pairs (key, value) to the hash table
/* Insert operation */
// Insert the key-value pair (key, value) into the hash table
map.set(12836, '小哈');
map.set(15937, '小啰');
map.set(16750, '小算');
map.set(13276, '小法');
map.set(10583, '小鸭');
/* Lookup */
/* Lookup operation */
// Look up key in the hash table to obtain value
let name = map.get(15937);
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
/* Remove operation */
// Remove the key-value pair (key, value) from the hash table
map.delete(10583);
```
```typescript title="hash_map.ts"
/* Initialize a hash table */
/* Initialize the hash table */
const map = new Map<number, string>();
/* Insertion */
// Add key-value pairs (key, value) to the hash table
/* Insert operation */
// Insert the key-value pair (key, value) into the hash table
map.set(12836, '小哈');
map.set(15937, '小啰');
map.set(16750, '小算');
map.set(13276, '小法');
map.set(10583, '小鸭');
console.info('\nAfter insertion, the hash table is\nKey -> Value');
console.info(map);
/* Lookup */
/* Lookup operation */
// Look up key in the hash table to obtain value
let name = map.get(15937);
console.info('\nLooking up student ID 15937 gives the name ' + name);
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
/* Remove operation */
// Remove the key-value pair (key, value) from the hash table
map.delete(10583);
console.info('\nAfter deleting 10583, the hash table is\nKey -> Value');
console.info(map);
```
```dart title="hash_map.dart"
/* Initialize a hash table */
Map<int, String> map = {};
/* Initialize the hash table */
final Map<int, String> map = {};
/* Insertion */
// Add key-value pairs (key, value) to the hash table
/* Insert operation */
// Insert the key-value pair (key, value) into the hash table
map[12836] = "小哈";
map[15937] = "小啰";
map[16750] = "小算";
map[13276] = "小法";
map[10583] = "小鸭";
/* Lookup */
/* Lookup operation */
// Look up key in the hash table to obtain value
String? name = map[15937];
final String? name = map[15937];
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
/* Remove operation */
// Remove the key-value pair (key, value) from the hash table
map.remove(10583);
```
```rust title="hash_map.rs"
use std::collections::HashMap;
/* Initialize a hash table */
let mut map: HashMap<i32, String> = HashMap::new();
// Initialize the hash table
let mut map = HashMap::new();
/* Insertion */
// Add key-value pairs (key, value) to the hash table
map.insert(12836, "小哈".to_string());
map.insert(15937, "小啰".to_string());
map.insert(16750, "小算".to_string());
map.insert(13276, "小法".to_string());
map.insert(10583, "小鸭".to_string());
// Insert operation
// Insert the key-value pair (key, value) into the hash table
map.insert(12836, "小哈");
map.insert(15937, "小啰");
map.insert(16750, "小算");
map.insert(13276, "小法");
map.insert(10583, "小鸭");
/* Lookup */
// Lookup operation
// Look up key in the hash table to obtain value
let _name: Option<&String> = map.get(&15937);
let name = map.get(&15937).copied().unwrap();
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
let _removed_value: Option<String> = map.remove(&10583);
// Remove operation
// Remove the key-value pair (key, value) from the hash table
_ = map.remove(&10583);
```
```c title="hash_map.c"
@@ -219,44 +216,44 @@ let _removed_value: Option<String> = map.remove(&10583);
```
```kotlin title="hash_map.kt"
/* Initialize a hash table */
val map = HashMap<Int,String>()
/* Initialize the hash table */
val map = HashMap<Int, String>()
/* Insertion */
// Add key-value pairs (key, value) to the hash table
/* Insert operation */
// Insert the key-value pair (key, value) into the hash table
map[12836] = "小哈"
map[15937] = "小啰"
map[16750] = "小算"
map[13276] = "小法"
map[10583] = "小鸭"
/* Lookup */
/* Lookup operation */
// Look up key in the hash table to obtain value
val name = map[15937]
/* Deletion */
// Remove a key-value pair (key, value) from the hash table
/* Remove operation */
// Remove the key-value pair (key, value) from the hash table
map.remove(10583)
```
```ruby title="hash_map.rb"
# Initialize a hash table
# Initialize the hash table
hmap = {}
# Insertion
# Add key-value pairs (key, value) to the hash table
# Insert operation
# Insert the key-value pair (key, value) into the hash table
hmap[12836] = "小哈"
hmap[15937] = "小啰"
hmap[16750] = "小算"
hmap[13276] = "小法"
hmap[10583] = "小鸭"
# Lookup
# Lookup operation
# Look up key in the hash table to obtain value
name = hmap[15937]
# Deletion
# Remove a key-value pair (key, value) from the hash table
# Remove operation
# Remove the key-value pair (key, value) from the hash table
hmap.delete(10583)
```
@@ -269,52 +266,59 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
# Traverse key-value pairs: key->value
for key, value in hmap.items():
print(key, "->", value)
# Traverse keys only: key
for key in hmap.keys():
print(key)
# Traverse values only: value
for value in hmap.values():
print(value)
for val in hmap.values():
print(val)
```
```cpp title="hash_map.cpp"
/* Traverse the hash table */
// Traverse key-value pairs: key->value
for (auto kv: map) {
for (auto kv : map) {
cout << kv.first << " -> " << kv.second << endl;
}
// Use an iterator to traverse key->value pairs
// Traverse key->value using an iterator
for (auto iter = map.begin(); iter != map.end(); iter++) {
cout << iter->first << "->" << iter->second << endl;
cout << iter->first << " -> " << iter->second << endl;
}
```
```java title="hash_map.java"
/* Traverse the hash table */
// Traverse key-value pairs: key->value
for (Map.Entry <Integer, String> kv: map.entrySet()) {
for (Map.Entry<Integer, String> kv : map.entrySet()) {
System.out.println(kv.getKey() + " -> " + kv.getValue());
}
// Traverse keys only: key
for (int key: map.keySet()) {
for (int key : map.keySet()) {
System.out.println(key);
}
// Traverse values only: value
for (String val: map.values()) {
for (String val : map.values()) {
System.out.println(val);
}
```
```csharp title="hash_map.cs"
/* Traverse the hash table */
// Traverse key-value pairs: Key->Value
// Traverse key-value pairs: key->value
foreach (var kv in map) {
Console.WriteLine(kv.Key + " -> " + kv.Value);
}
// Traverse keys only: key
foreach (int key in map.Keys) {
Console.WriteLine(key);
}
// Traverse values only: value
foreach (string val in map.Values) {
Console.WriteLine(val);
@@ -327,10 +331,12 @@ foreach (string val in map.Values) {
for key, value := range hmap {
fmt.Println(key, "->", value)
}
// Traverse keys only: key
for key := range hmap {
fmt.Println(key)
}
// Traverse values only: value
for _, value := range hmap {
fmt.Println(value)
@@ -339,15 +345,17 @@ for _, value := range hmap {
```swift title="hash_map.swift"
/* Traverse the hash table */
// Traverse key-value pairs: Key->Value
// Traverse key-value pairs: key->value
for (key, value) in map {
print("\(key) -> \(value)")
}
// Traverse keys only: Key
// Traverse keys only: key
for key in map.keys {
print(key)
}
// Traverse values only: Value
// Traverse values only: value
for value in map.values {
print(value)
}
@@ -355,15 +363,17 @@ for value in map.values {
```javascript title="hash_map.js"
/* Traverse the hash table */
console.info('\nTraverse key-value pairs: Key->Value');
// Traverse key-value pairs: key->value
for (const [k, v] of map.entries()) {
console.info(k + ' -> ' + v);
}
console.info('\nTraverse keys only: Key');
// Traverse keys only: key
for (const k of map.keys()) {
console.info(k);
}
console.info('\nTraverse values only: Value');
// Traverse values only: value
for (const v of map.values()) {
console.info(v);
}
@@ -371,15 +381,17 @@ for (const v of map.values()) {
```typescript title="hash_map.ts"
/* Traverse the hash table */
console.info('\nTraverse key-value pairs: Key->Value');
// Traverse key-value pairs: key->value
for (const [k, v] of map.entries()) {
console.info(k + ' -> ' + v);
}
console.info('\nTraverse keys only: Key');
// Traverse keys only: key
for (const k of map.keys()) {
console.info(k);
}
console.info('\nTraverse values only: Value');
// Traverse values only: value
for (const v of map.values()) {
console.info(v);
}
@@ -387,35 +399,29 @@ for (const v of map.values()) {
```dart title="hash_map.dart"
/* Traverse the hash table */
// Traverse key-value pairs: Key->Value
map.forEach((key, value) {
print('$key -> $value');
});
// Traverse key-value pairs: key->value
map.forEach((key, value) => print("$key -> $value"));
// Traverse keys only: Key
map.keys.forEach((key) {
print(key);
});
// Traverse keys only: key
map.keys.forEach((key) => print(key));
// Traverse values only: Value
map.values.forEach((value) {
print(value);
});
// Traverse values only: value
map.values.forEach((value) => print(value));
```
```rust title="hash_map.rs"
/* Traverse the hash table */
// Traverse key-value pairs: Key->Value
// Traverse the hash table
// Traverse key-value pairs: key->value
for (key, value) in &map {
println!("{key} -> {value}");
}
// Traverse keys only: Key
// Traverse keys only: key
for key in map.keys() {
println!("{key}");
}
// Traverse values only: Value
// Traverse values only: value
for value in map.values() {
println!("{value}");
}
@@ -431,10 +437,12 @@ for value in map.values() {
for ((key, value) in map) {
println("$key -> $value")
}
// Traverse keys only: key
for (key in map.keys) {
println(key)
}
// Traverse values only: value
for (_val in map.values) {
println(_val)
@@ -454,4 +462,4 @@ hmap.values.each { |val| puts val }
```
<!-- [tutor]{hash_map_traversal_tutor} -->
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20hash%20table%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20Insertion%0A%20%20%20%20%23%20Add%20key-value%20pairs%20%28key%2C%20value%29%20to%20the%20hash%20table%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20Traverse%20the%20hash%20table%0A%20%20%20%20%23%20Traverse%20key-value%20pairs%3A%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20Traverse%20keys%20only%3A%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20Traverse%20values%20only%3A%20value%0A%20%20%20%20for%20value%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28value%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20hash%20table%0A%20%20%20%20hmap%20%3D%20%7B%7D%0A%20%20%20%20%0A%20%20%20%20%23%20Insertion%0A%20%20%20%20%23%20Add%20key-value%20pairs%20%28key%2C%20value%29%20to%20the%20hash%20table%0A%20%20%20%20hmap%5B12836%5D%20%3D%20%22%E5%B0%8F%E5%93%88%22%0A%20%20%20%20hmap%5B15937%5D%20%3D%20%22%E5%B0%8F%E5%95%B0%22%0A%20%20%20%20hmap%5B16750%5D%20%3D%20%22%E5%B0%8F%E7%AE%97%22%0A%20%20%20%20hmap%5B13276%5D%20%3D%20%22%E5%B0%8F%E6%B3%95%22%0A%20%20%20%20hmap%5B10583%5D%20%3D%20%22%E5%B0%8F%E9%B8%AD%22%0A%20%20%20%20%0A%20%20%20%20%23%20Traverse%20the%20hash%20table%0A%20%20%20%20%23%20Traverse%20key-value%20pairs%3A%20key-%3Evalue%0A%20%20%20%20for%20key%2C%20value%20in%20hmap.items%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%2C%20%22-%3E%22%2C%20value%29%0A%20%20%20%20%23%20Traverse%20keys%20only%3A%20key%0A%20%20%20%20for%20key%20in%20hmap.keys%28%29%3A%0A%20%20%20%20%20%20%20%20print%28key%29%0A%20%20%20%20%23%20Traverse%20values%20only%3A%20value%0A%20%20%20%20for%20val%20in%20hmap.values%28%29%3A%0A%20%20%20%20%20%20%20%20print%28val%29&cumulative=false&curInstr=8&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false

View File

@@ -6,26 +6,26 @@ min_heap, flag = [], 1
max_heap, flag = [], -1
# Python's heapq module implements a min heap by default
# Negate elements before insertion to reverse their order and implement a max heap
# Here, flag = 1 gives a min heap and flag = -1 gives a max heap
# Negate each element before pushing it onto the heap to reverse the ordering and implement a max heap
# In this example, flag = 1 represents a min heap and flag = -1 represents a max heap
# Insert elements into the heap
# Push an element onto the heap
heapq.heappush(max_heap, flag * 1)
heapq.heappush(max_heap, flag * 3)
heapq.heappush(max_heap, flag * 2)
heapq.heappush(max_heap, flag * 5)
heapq.heappush(max_heap, flag * 4)
# Access the root element
peek: int = flag * max_heap[0] # 5
# Get the top element of the heap
peek: int = flag * max_heap[0] # 5
# Remove root elements
# Removed elements form a descending sequence
val = flag * heapq.heappop(max_heap) # 5
val = flag * heapq.heappop(max_heap) # 4
val = flag * heapq.heappop(max_heap) # 3
val = flag * heapq.heappop(max_heap) # 2
val = flag * heapq.heappop(max_heap) # 1
# Pop the top element from the heap
# The elements are popped in descending order
val = flag * heapq.heappop(max_heap) # 5
val = flag * heapq.heappop(max_heap) # 4
val = flag * heapq.heappop(max_heap) # 3
val = flag * heapq.heappop(max_heap) # 2
val = flag * heapq.heappop(max_heap) # 1
# Get the heap size
size: int = len(max_heap)
@@ -33,30 +33,31 @@ size: int = len(max_heap)
# Check whether the heap is empty
is_empty: bool = not max_heap
# Build a heap from a list
# Build a heap from an input list
# The time complexity is O(n), not O(nlogn)
min_heap: list[int] = [1, 3, 2, 5, 4]
heapq.heapify(min_heap)
```
```cpp title="heap.cpp"
/* Initialize a heap */
/* Initialize the heap */
// Initialize a min heap
priority_queue<int, vector<int>, greater<int>> minHeap;
// Initialize a max heap
priority_queue<int, vector<int>, less<int>> maxHeap;
/* Insert elements into the heap */
/* Push an element onto the heap */
maxHeap.push(1);
maxHeap.push(3);
maxHeap.push(2);
maxHeap.push(5);
maxHeap.push(4);
/* Access the root element */
/* Get the top element of the heap */
int peek = maxHeap.top(); // 5
/* Remove root elements */
// Removed elements form a descending sequence
/* Pop the top element from the heap */
// The elements are popped in descending order
maxHeap.pop(); // 5
maxHeap.pop(); // 4
maxHeap.pop(); // 3
@@ -69,30 +70,31 @@ int size = maxHeap.size();
/* Check whether the heap is empty */
bool isEmpty = maxHeap.empty();
/* Build a heap from a list */
/* Build a heap from an input list */
// The time complexity is O(n), not O(nlogn)
vector<int> input{1, 3, 2, 5, 4};
minHeap = priority_queue<int, vector<int>, greater<int>>(input.begin(), input.end());
```
```java title="heap.java"
/* Initialize a heap */
/* Initialize heaps */
// Initialize a min heap
Queue<Integer> minHeap = new PriorityQueue<>();
// Initialize a max heap by changing the Comparator with a lambda expression
// Initialize a max heap by supplying a lambda expression as the Comparator
Queue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
/* Insert elements into the heap */
/* Push an element onto the heap */
maxHeap.offer(1);
maxHeap.offer(3);
maxHeap.offer(2);
maxHeap.offer(5);
maxHeap.offer(4);
/* Access the root element */
/* Get the top element of the heap */
int peek = maxHeap.peek(); // 5
/* Remove root elements */
// Removed elements form a descending sequence
/* Pop the top element from the heap */
// The elements are popped in descending order
peek = maxHeap.poll(); // 5
peek = maxHeap.poll(); // 4
peek = maxHeap.poll(); // 3
@@ -105,34 +107,35 @@ int size = maxHeap.size();
/* Check whether the heap is empty */
boolean isEmpty = maxHeap.isEmpty();
/* Build a heap from a list */
/* Build a heap from an input list */
// The time complexity is O(n), not O(nlogn)
minHeap = new PriorityQueue<>(Arrays.asList(1, 3, 2, 5, 4));
```
```csharp title="heap.cs"
/* Initialize a heap */
/* Initialize heaps */
// Initialize a min heap
PriorityQueue<int, int> minHeap = new();
// Initialize a max heap by changing the Comparer with a lambda expression
// Initialize a max heap (use a lambda expression to customize the Comparer)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.Create((x, y) => y.CompareTo(x)));
/* Insert elements into the heap */
/* Push an element onto the heap */
maxHeap.Enqueue(1, 1);
maxHeap.Enqueue(3, 3);
maxHeap.Enqueue(2, 2);
maxHeap.Enqueue(5, 5);
maxHeap.Enqueue(4, 4);
/* Access the root element */
int peek = maxHeap.Peek();//5
/* Get the top element of the heap */
int peek = maxHeap.Peek(); // 5
/* Remove root elements */
// Removed elements form a descending sequence
peek = maxHeap.Dequeue(); // 5
peek = maxHeap.Dequeue(); // 4
peek = maxHeap.Dequeue(); // 3
peek = maxHeap.Dequeue(); // 2
peek = maxHeap.Dequeue(); // 1
/* Pop the top element from the heap */
// The elements are popped in descending order
peek = maxHeap.Dequeue(); // 5
peek = maxHeap.Dequeue(); // 4
peek = maxHeap.Dequeue(); // 3
peek = maxHeap.Dequeue(); // 2
peek = maxHeap.Dequeue(); // 1
/* Get the heap size */
int size = maxHeap.Count;
@@ -140,7 +143,8 @@ int size = maxHeap.Count;
/* Check whether the heap is empty */
bool isEmpty = maxHeap.Count == 0;
/* Build a heap from a list */
/* Build a heap from an input list */
// The time complexity is O(n), not O(nlogn)
minHeap = new PriorityQueue<int, int>([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]);
```
@@ -149,94 +153,96 @@ minHeap = new PriorityQueue<int, int>([(1, 1), (3, 3), (2, 2), (5, 5), (4, 4)]);
// Implementing heap.Interface also requires implementing sort.Interface
type intHeap []any
// Push implements the heap.Interface method for inserting an element
// Push is a heap.Interface function that pushes an element onto the heap
func (h *intHeap) Push(x any) {
// Push and Pop use pointer receivers
// because they change the slice length as well as its contents.
// because they modify the slice length as well as its contents.
*h = append(*h, x.(int))
}
// Pop implements the heap.Interface method used to remove the root element
// Pop is a heap.Interface function that pops the top element from the heap
func (h *intHeap) Pop() any {
// The element to remove has been placed at the end
// The element to remove is stored at the end
last := (*h)[len(*h)-1]
*h = (*h)[:len(*h)-1]
return last
}
// Len implements a sort.Interface method
// Len implements the sort.Interface length method
func (h *intHeap) Len() int {
return len(*h)
}
// Less implements a sort.Interface method
// Less implements the sort.Interface comparison method
func (h *intHeap) Less(i, j int) bool {
// For a min heap, change this to a less-than comparison
// For a min heap, change the comparison to less than
return (*h)[i].(int) > (*h)[j].(int)
}
// Swap implements a sort.Interface method
// Swap implements the sort.Interface swap method
func (h *intHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
// Top returns the root element
// Top returns the top element of the heap
func (h *intHeap) Top() any {
return (*h)[0]
}
/* Driver Code */
func TestHeap(t *testing.T) {
/* Initialize a heap */
/* Initialize the heap */
// Initialize a max heap
maxHeap := &intHeap{}
heap.Init(maxHeap)
/* Insert elements into the heap */
// Call the heap.Interface methods to add elements
/* Push an element onto the heap */
// Call a heap.Interface function to add an element
heap.Push(maxHeap, 1)
heap.Push(maxHeap, 3)
heap.Push(maxHeap, 2)
heap.Push(maxHeap, 4)
heap.Push(maxHeap, 5)
heap.Push(maxHeap, 4)
PrintHeap(*maxHeap)
/* Access the root element */
/* Get the top element of the heap */
top := maxHeap.Top()
fmt.Printf("The root element is %d\n", top)
fmt.Printf("Top element of the heap: %d\n", top)
/* Remove root elements */
// Call the heap.Interface methods to remove elements
heap.Pop(maxHeap) // 5
heap.Pop(maxHeap) // 4
heap.Pop(maxHeap) // 3
heap.Pop(maxHeap) // 2
heap.Pop(maxHeap) // 1
/* Pop the top element from the heap */
// Call a heap.Interface function to remove an element
fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 5
fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 4
fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 3
fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 2
fmt.Printf("Element popped from the heap: %d\n", heap.Pop(maxHeap)) // 1
/* Get the heap size */
size := len(*maxHeap)
fmt.Printf("The heap contains %d elements\n", size)
fmt.Printf("Number of elements in the heap: %d\n", size)
/* Check whether the heap is empty */
isEmpty := len(*maxHeap) == 0
fmt.Printf("Is the heap empty: %t\n", isEmpty)
fmt.Printf("Is the heap empty? %t\n", isEmpty)
}
```
```swift title="heap.swift"
/* Initialize a heap */
// Swift's Heap type supports both minimum and maximum operations and requires swift-collections
import HeapModule
/* Initialize the heap */
// Swift's Heap type supports both max heap and min heap operations and requires the swift-collections package
var heap = Heap<Int>()
/* Insert elements into the heap */
/* Push an element onto the heap */
heap.insert(1)
heap.insert(3)
heap.insert(2)
heap.insert(5)
heap.insert(4)
/* Access the root element */
var peek = heap.max()!
/* Get the maximum element of the heap */
var peek = heap.max()
/* Remove root elements */
/* Remove the maximum element from the heap */
peek = heap.removeMax() // 5
peek = heap.removeMax() // 4
peek = heap.removeMax() // 3
@@ -249,7 +255,8 @@ let size = heap.count
/* Check whether the heap is empty */
let isEmpty = heap.isEmpty
/* Build a heap from a list */
/* Build a heap from an input list */
// The time complexity is O(n), not O(nlogn)
let heap2 = Heap([1, 3, 2, 5, 4])
```
@@ -266,32 +273,33 @@ let heap2 = Heap([1, 3, 2, 5, 4])
```
```rust title="heap.rs"
use std::collections::BinaryHeap;
use std::cmp::Reverse;
use std::{cmp::Reverse, collections::BinaryHeap};
/* Initialize a heap */
/* Initialize the heap */
// Initialize a min heap
let mut min_heap = BinaryHeap::<Reverse<i32>>::new();
// Rust's BinaryHeap is a max heap; wrap elements in Reverse to create a min heap
#[allow(unused_assignments)]
let mut min_heap = BinaryHeap::new();
// Initialize a max heap
let mut max_heap = BinaryHeap::new();
/* Insert elements into the heap */
/* Push an element onto the heap */
max_heap.push(1);
max_heap.push(3);
max_heap.push(2);
max_heap.push(5);
max_heap.push(4);
/* Access the root element */
let peek = max_heap.peek().unwrap(); // 5
/* Get the top element of the heap */
let peek = max_heap.peek().unwrap(); // 5
/* Remove root elements */
// Removed elements form a descending sequence
let peek = max_heap.pop().unwrap(); // 5
let peek = max_heap.pop().unwrap(); // 4
let peek = max_heap.pop().unwrap(); // 3
let peek = max_heap.pop().unwrap(); // 2
let peek = max_heap.pop().unwrap(); // 1
/* Pop the top element from the heap */
// The elements are popped in descending order
let peek = max_heap.pop().unwrap(); // 5
let peek = max_heap.pop().unwrap(); // 4
let peek = max_heap.pop().unwrap(); // 3
let peek = max_heap.pop().unwrap(); // 2
let peek = max_heap.pop().unwrap(); // 1
/* Get the heap size */
let size = max_heap.len();
@@ -299,8 +307,9 @@ let size = max_heap.len();
/* Check whether the heap is empty */
let is_empty = max_heap.is_empty();
/* Build a heap from a list */
let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]);
/* Build a heap from an input list */
// The time complexity is O(n), not O(nlogn)
min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse(5), Reverse(4)]);
```
```c title="heap.c"
@@ -308,24 +317,24 @@ let min_heap = BinaryHeap::from(vec![Reverse(1), Reverse(3), Reverse(2), Reverse
```
```kotlin title="heap.kt"
/* Initialize a heap */
/* Initialize heaps */
// Initialize a min heap
var minHeap = PriorityQueue<Int>()
// Initialize a max heap by changing the Comparator with a lambda expression
// Initialize a max heap by supplying a lambda expression as the Comparator
val maxHeap = PriorityQueue { a: Int, b: Int -> b - a }
/* Insert elements into the heap */
/* Push an element onto the heap */
maxHeap.offer(1)
maxHeap.offer(3)
maxHeap.offer(2)
maxHeap.offer(5)
maxHeap.offer(4)
/* Access the root element */
/* Get the top element of the heap */
var peek = maxHeap.peek() // 5
/* Remove root elements */
// Removed elements form a descending sequence
/* Pop the top element from the heap */
// The elements are popped in descending order
peek = maxHeap.poll() // 5
peek = maxHeap.poll() // 4
peek = maxHeap.poll() // 3
@@ -338,8 +347,9 @@ val size = maxHeap.size
/* Check whether the heap is empty */
val isEmpty = maxHeap.isEmpty()
/* Build a heap from a list */
minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4))
/* Build a heap from an input list */
// The time complexity is O(n), not O(nlogn)
minHeap = PriorityQueue(mutableListOf<Int?>(1, 3, 2, 5, 4))
```
```ruby title="heap.rb"
@@ -347,4 +357,4 @@ minHeap = PriorityQueue(mutableListOf(1, 3, 2, 5, 4))
```
<!-- [tutor]{heap_operations_tutor} -->
https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20min%20heap%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20Initialize%20a%20max%20heap%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%27s%20heapq%20module%20implements%20a%20min%20heap%20by%20default%0A%20%20%20%20%23%20Negate%20elements%20before%20insertion%20to%20reverse%20their%20order%20and%20implement%20a%20max%20heap%0A%20%20%20%20%23%20Here%2C%20flag%20%3D%201%20gives%20a%20min%20heap%20and%20flag%20%3D%20-1%20gives%20a%20max%20heap%0A%20%20%20%20%0A%20%20%20%20%23%20Insert%20elements%20into%20the%20heap%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20Access%20the%20root%20element%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20Remove%20root%20elements%0A%20%20%20%20%23%20Removed%20elements%20form%20a%20descending%20sequence%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20Get%20the%20heap%20size%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20Check%20whether%20the%20heap%20is%20empty%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20Build%20a%20heap%20from%20a%20list%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=import%20heapq%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20min%20heap%0A%20%20%20%20min_heap%2C%20flag%20%3D%20%5B%5D%2C%201%0A%20%20%20%20%23%20Initialize%20a%20max%20heap%0A%20%20%20%20max_heap%2C%20flag%20%3D%20%5B%5D%2C%20-1%0A%20%20%20%20%0A%20%20%20%20%23%20Python%27s%20heapq%20module%20implements%20a%20min%20heap%20by%20default%0A%20%20%20%20%23%20Negate%20elements%20before%20insertion%20to%20reverse%20their%20order%20and%20implement%20a%20max%20heap%0A%20%20%20%20%23%20Here%2C%20flag%20%3D%201%20gives%20a%20min%20heap%20and%20flag%20%3D%20-1%20gives%20a%20max%20heap%0A%20%20%20%20%0A%20%20%20%20%23%20Insert%20elements%20into%20the%20heap%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%201%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%203%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%202%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%205%29%0A%20%20%20%20heapq.heappush%28max_heap%2C%20flag%20%2A%204%29%0A%20%20%20%20%0A%20%20%20%20%23%20Access%20the%20root%20element%0A%20%20%20%20peek%20%3D%20flag%20%2A%20max_heap%5B0%5D%20%23%205%0A%20%20%20%20%0A%20%20%20%20%23%20Remove%20root%20elements%0A%20%20%20%20%23%20Removed%20elements%20form%20a%20descending%20sequence%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%205%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%204%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%203%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%202%0A%20%20%20%20val%20%3D%20flag%20%2A%20heapq.heappop%28max_heap%29%20%23%201%0A%20%20%20%20%0A%20%20%20%20%23%20Get%20the%20heap%20size%0A%20%20%20%20size%20%3D%20len%28max_heap%29%0A%20%20%20%20%0A%20%20%20%20%23%20Check%20whether%20the%20heap%20is%20empty%0A%20%20%20%20is_empty%20%3D%20not%20max_heap%0A%20%20%20%20%0A%20%20%20%20%23%20Build%20a%20heap%20from%20a%20list%0A%20%20%20%20%23%20The%20time%20complexity%20is%20O%28n%29%2C%20not%20O%28nlogn%29%0A%20%20%20%20min_heap%20%3D%20%5B1%2C%203%2C%202%2C%205%2C%204%5D%0A%20%20%20%20heapq.heapify%28min_heap%29&cumulative=false&curInstr=3&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false

View File

@@ -2,23 +2,23 @@
```python title="deque.py"
from collections import deque
# Initialize a deque
# Initialize the deque
deq: deque[int] = deque()
# Enqueue elements
deq.append(2) # Add at the rear
deq.append(2) # Add to the rear
deq.append(5)
deq.append(4)
deq.appendleft(3) # Add at the front
deq.appendleft(3) # Add to the front
deq.appendleft(1)
# Access elements
# Access an element
front: int = deq[0] # Front element
rear: int = deq[-1] # Rear element
# Dequeue elements
pop_front: int = deq.popleft() # Remove the front element
pop_rear: int = deq.pop() # Remove the rear element
# Dequeue an element
pop_front: int = deq.popleft() # Dequeue the front element
pop_rear: int = deq.pop() # Dequeue the rear element
# Get the deque size
size: int = len(deq)
@@ -28,23 +28,23 @@ is_empty: bool = len(deq) == 0
```
```cpp title="deque.cpp"
/* Initialize a deque */
/* Initialize the deque */
deque<int> deque;
/* Enqueue elements */
deque.push_back(2); // Add at the rear
deque.push_back(2); // Add to the rear
deque.push_back(5);
deque.push_back(4);
deque.push_front(3); // Add at the front
deque.push_front(3); // Add to the front
deque.push_front(1);
/* Access elements */
/* Access an element */
int front = deque.front(); // Front element
int back = deque.back(); // Rear element
int back = deque.back(); // Rear element
/* Dequeue elements */
deque.pop_front(); // Remove the front element
deque.pop_back(); // Remove the rear element
/* Dequeue an element */
deque.pop_front(); // Dequeue the front element
deque.pop_back(); // Dequeue the rear element
/* Get the deque size */
int size = deque.size();
@@ -54,23 +54,23 @@ bool empty = deque.empty();
```
```java title="deque.java"
/* Initialize a deque */
/* Initialize the deque */
Deque<Integer> deque = new LinkedList<>();
/* Enqueue elements */
deque.offerLast(2); // Add at the rear
deque.offerLast(2); // Add to the rear
deque.offerLast(5);
deque.offerLast(4);
deque.offerFirst(3); // Add at the front
deque.offerFirst(3); // Add to the front
deque.offerFirst(1);
/* Access elements */
int peekFirst = deque.peekFirst(); // Front element
int peekLast = deque.peekLast(); // Rear element
/* Access an element */
int peekFirst = deque.peekFirst(); // Front element
int peekLast = deque.peekLast(); // Rear element
/* Dequeue elements */
int popFirst = deque.pollFirst(); // Remove the front element
int popLast = deque.pollLast(); // Remove the rear element
/* Dequeue an element */
int popFirst = deque.pollFirst(); // Dequeue the front element
int popLast = deque.pollLast(); // Dequeue the rear element
/* Get the deque size */
int size = deque.size();
@@ -80,24 +80,24 @@ boolean isEmpty = deque.isEmpty();
```
```csharp title="deque.cs"
/* Initialize a deque */
// In C#, use a LinkedList as a deque
/* Initialize the deque */
// In C#, use the linked list LinkedList as a deque
LinkedList<int> deque = new();
/* Enqueue elements */
deque.AddLast(2); // Add at the rear
deque.AddLast(2); // Add to the rear
deque.AddLast(5);
deque.AddLast(4);
deque.AddFirst(3); // Add at the front
deque.AddFirst(3); // Add to the front
deque.AddFirst(1);
/* Access elements */
int peekFirst = deque.First.Value; // Front element
int peekLast = deque.Last.Value; // Rear element
/* Access an element */
int? peekFirst = deque.First?.Value; // Front element
int? peekLast = deque.Last?.Value; // Rear element
/* Dequeue elements */
deque.RemoveFirst(); // Remove the front element
deque.RemoveLast(); // Remove the rear element
/* Dequeue an element */
deque.RemoveFirst(); // Dequeue the front element
deque.RemoveLast(); // Dequeue the rear element
/* Get the deque size */
int size = deque.Count;
@@ -107,24 +107,24 @@ bool isEmpty = deque.Count == 0;
```
```go title="deque_test.go"
/* Initialize a deque */
// In Go, use a list as a deque
/* Initialize the deque */
// In Go, list can be used as a deque
deque := list.New()
/* Enqueue elements */
deque.PushBack(2) // Add at the rear
deque.PushBack(2) // Add to the rear
deque.PushBack(5)
deque.PushBack(4)
deque.PushFront(3) // Add at the front
deque.PushFront(3) // Add to the front
deque.PushFront(1)
/* Access elements */
/* Access an element */
front := deque.Front() // Front element
rear := deque.Back() // Rear element
rear := deque.Back() // Rear element
/* Dequeue elements */
deque.Remove(front) // Remove the front element
deque.Remove(rear) // Remove the rear element
/* Dequeue an element */
deque.Remove(front) // Dequeue the front element
deque.Remove(rear) // Dequeue the rear element
/* Get the deque size */
size := deque.Len()
@@ -134,25 +134,25 @@ isEmpty := deque.Len() == 0
```
```swift title="deque.swift"
/* Initialize a deque */
// Swift has no built-in deque class; use an Array as a deque
/* Initialize the deque */
// The Swift standard library has no built-in deque class; Array can be used as a deque
var deque: [Int] = []
/* Enqueue elements */
deque.append(2) // Add at the rear
deque.append(2) // Add to the rear
deque.append(5)
deque.append(4)
deque.insert(3, at: 0) // Add at the front
deque.insert(3, at: 0) // Add to the front
deque.insert(1, at: 0)
/* Access elements */
/* Access an element */
let peekFirst = deque.first! // Front element
let peekLast = deque.last! // Rear element
/* Dequeue elements */
// When using an Array, popFirst takes O(n) time
let popFirst = deque.removeFirst() // Remove the front element
let popLast = deque.removeLast() // Remove the rear element
/* Dequeue an element */
// When using Array to simulate a deque, removeFirst has O(n) complexity
let popFirst = deque.removeFirst() // Dequeue the front element
let popLast = deque.removeLast() // Dequeue the rear element
/* Get the deque size */
let size = deque.count
@@ -162,24 +162,24 @@ let isEmpty = deque.isEmpty
```
```javascript title="deque.js"
/* Initialize a deque */
// JavaScript has no built-in deque; use an Array instead
/* Initialize the deque */
// JavaScript has no built-in deque; use an Array as a deque
const deque = [];
/* Enqueue elements */
deque.push(2);
deque.push(5);
deque.push(4);
// Note that this is an array, so unshift() takes O(n) time
// Note: because this uses an array, unshift() has O(n) time complexity
deque.unshift(3);
deque.unshift(1);
/* Access elements */
/* Access an element */
const peekFirst = deque[0];
const peekLast = deque[deque.length - 1];
/* Dequeue elements */
// Note that this is an array, so shift() takes O(n) time
/* Dequeue an element */
// Note: because this uses an array, shift() has O(n) time complexity
const popFront = deque.shift();
const popBack = deque.pop();
@@ -191,24 +191,24 @@ const isEmpty = size === 0;
```
```typescript title="deque.ts"
/* Initialize a deque */
// TypeScript has no built-in deque; use an Array instead
/* Initialize the deque */
// TypeScript has no built-in deque; use an Array as a deque instead
const deque: number[] = [];
/* Enqueue elements */
deque.push(2);
deque.push(5);
deque.push(4);
// Note that this is an array, so unshift() takes O(n) time
// Note: because this uses an array, unshift() has O(n) time complexity
deque.unshift(3);
deque.unshift(1);
/* Access elements */
/* Access an element */
const peekFirst: number = deque[0];
const peekLast: number = deque[deque.length - 1];
/* Dequeue elements */
// Note that this is an array, so shift() takes O(n) time
/* Dequeue an element */
// Note: because this uses an array, shift() has O(n) time complexity
const popFront: number = deque.shift() as number;
const popBack: number = deque.pop() as number;
@@ -220,59 +220,55 @@ const isEmpty: boolean = size === 0;
```
```dart title="deque.dart"
/* Initialize a deque */
/* Initialize the deque */
// In Dart, Queue is defined as a deque
Queue<int> deque = Queue<int>();
final Queue<int> deque = Queue();
/* Enqueue elements */
deque.addLast(2); // Add at the rear
deque.addLast(2); // Add to the rear
deque.addLast(5);
deque.addLast(4);
deque.addFirst(3); // Add at the front
deque.addFirst(3); // Add to the front
deque.addFirst(1);
/* Access elements */
int peekFirst = deque.first; // Front element
int peekLast = deque.last; // Rear element
/* Access an element */
final int peekFirst = deque.first; // Front element
final int peekLast = deque.last; // Rear element
/* Dequeue elements */
int popFirst = deque.removeFirst(); // Remove the front element
int popLast = deque.removeLast(); // Remove the rear element
/* Dequeue an element */
final int popFirst = deque.removeFirst(); // Dequeue the front element
final int popLast = deque.removeLast(); // Dequeue the rear element
/* Get the deque size */
int size = deque.length;
final int size = deque.length;
/* Check whether the deque is empty */
bool isEmpty = deque.isEmpty;
final bool isEmpty = deque.isEmpty;
```
```rust title="deque.rs"
/* Initialize a deque */
let mut deque: VecDeque<u32> = VecDeque::new();
// Initialize the deque
let mut deque: VecDeque<i32> = VecDeque::new();
/* Enqueue elements */
deque.push_back(2); // Add at the rear
deque.push_back(2); // Add to the rear
deque.push_back(5);
deque.push_back(4);
deque.push_front(3); // Add at the front
deque.push_front(3); // Add to the front
deque.push_front(1);
/* Access elements */
if let Some(front) = deque.front() { // Front element
}
if let Some(rear) = deque.back() { // Rear element
}
// Access an element
let peek_first = deque.front().unwrap(); // Front element
let peek_last = deque.back().unwrap(); // Rear element
/* Dequeue elements */
if let Some(pop_front) = deque.pop_front() { // Remove the front element
}
if let Some(pop_rear) = deque.pop_back() { // Remove the rear element
}
// Dequeue an element
let pop_first = deque.pop_front().unwrap(); // Dequeue the front element
let pop_last = deque.pop_back().unwrap(); // Dequeue the rear element
/* Get the deque size */
// Get the deque size
let size = deque.len();
/* Check whether the deque is empty */
// Check whether the deque is empty
let is_empty = deque.is_empty();
```
@@ -281,23 +277,23 @@ let is_empty = deque.is_empty();
```
```kotlin title="deque.kt"
/* Initialize a deque */
/* Initialize the deque */
val deque = LinkedList<Int>()
/* Enqueue elements */
deque.offerLast(2) // Add at the rear
deque.offerLast(2) // Add to the rear
deque.offerLast(5)
deque.offerLast(4)
deque.offerFirst(3) // Add at the front
deque.offerFirst(3) // Add to the front
deque.offerFirst(1)
/* Access elements */
/* Access an element */
val peekFirst = deque.peekFirst() // Front element
val peekLast = deque.peekLast() // Rear element
val peekLast = deque.peekLast() // Rear element
/* Dequeue elements */
val popFirst = deque.pollFirst() // Remove the front element
val popLast = deque.pollLast() // Remove the rear element
/* Dequeue an element */
val popFirst = deque.pollFirst() // Dequeue the front element
val popLast = deque.pollLast() // Dequeue the rear element
/* Get the deque size */
val size = deque.size
@@ -307,24 +303,24 @@ val isEmpty = deque.isEmpty()
```
```ruby title="deque.rb"
# Initialize a deque
# Ruby has no built-in deque; use an Array instead
# Initialize the deque
# Ruby has no built-in deque class; use an Array as a deque
deque = []
# Enqueue elements
deque << 2
deque << 5
deque << 4
# Note that this is an array, so Array#unshift takes O(n) time
# Note that Array#unshift has O(n) time complexity because the underlying structure is an array
deque.unshift(3)
deque.unshift(1)
# Access elements
# Access an element
peek_first = deque.first
peek_last = deque.last
# Dequeue elements
# Note that this is an array, so Array#shift takes O(n) time
# Dequeue an element
# Note that Array#shift has O(n) time complexity because the underlying structure is an array
pop_front = deque.shift
pop_back = deque.pop

View File

@@ -2,9 +2,9 @@
```python title="queue.py"
from collections import deque
# Initialize a queue
# In Python, we usually use the deque class as a queue
# Although queue.Queue() is a dedicated queue class, it is less convenient and is not recommended here
# Initialize the queue
# In Python, we generally use the deque class as a queue
# Although queue.Queue() is a dedicated queue class, it is less convenient to use and is therefore not recommended
que: deque[int] = deque()
# Enqueue elements
@@ -28,7 +28,7 @@ is_empty: bool = len(que) == 0
```
```cpp title="queue.cpp"
/* Initialize a queue */
/* Initialize the queue */
queue<int> queue;
/* Enqueue elements */
@@ -52,7 +52,7 @@ bool empty = queue.empty();
```
```java title="queue.java"
/* Initialize a queue */
/* Initialize the queue */
Queue<Integer> queue = new LinkedList<>();
/* Enqueue elements */
@@ -76,7 +76,7 @@ boolean isEmpty = queue.isEmpty();
```
```csharp title="queue.cs"
/* Initialize a queue */
/* Initialize the queue */
Queue<int> queue = new();
/* Enqueue elements */
@@ -100,8 +100,8 @@ bool isEmpty = queue.Count == 0;
```
```go title="queue_test.go"
/* Initialize a queue */
// In Go, use a list as a queue
/* Initialize the queue */
// In Go, use list as a queue
queue := list.New()
/* Enqueue elements */
@@ -126,8 +126,8 @@ isEmpty := queue.Len() == 0
```
```swift title="queue.swift"
/* Initialize a queue */
// Swift has no built-in queue class; use an Array as a queue
/* Initialize the queue */
// The Swift standard library has no built-in queue class; Array can be used as a queue
var queue: [Int] = []
/* Enqueue elements */
@@ -141,7 +141,7 @@ queue.append(4)
let peek = queue.first!
/* Dequeue an element */
// Because this is an array, removeFirst takes O(n) time
// When using Array as a queue, removeFirst has O(n) time complexity
let pop = queue.removeFirst()
/* Get the queue size */
@@ -152,8 +152,8 @@ let isEmpty = queue.isEmpty
```
```javascript title="queue.js"
/* Initialize a queue */
// JavaScript has no built-in queue; use an Array as a queue
/* Initialize the queue */
// JavaScript has no built-in queue; an Array can be used as a queue
const queue = [];
/* Enqueue elements */
@@ -167,19 +167,19 @@ queue.push(4);
const peek = queue[0];
/* Dequeue an element */
// The underlying structure is an array, so shift() takes O(n) time
// The underlying structure is an array, so shift() has O(n) time complexity
const pop = queue.shift();
/* Get the queue size */
const size = queue.length;
/* Check whether the queue is empty */
const empty = queue.length === 0;
const isEmpty = queue.length === 0;
```
```typescript title="queue.ts"
/* Initialize a queue */
// TypeScript has no built-in queue; use an Array as a queue
/* Initialize the queue */
// TypeScript has no built-in queue; an Array can be used as a queue
const queue: number[] = [];
/* Enqueue elements */
@@ -193,20 +193,20 @@ queue.push(4);
const peek = queue[0];
/* Dequeue an element */
// The underlying structure is an array, so shift() takes O(n) time
// The underlying structure is an array, so shift() has O(n) time complexity
const pop = queue.shift();
/* Get the queue size */
const size = queue.length;
/* Check whether the queue is empty */
const empty = queue.length === 0;
const isEmpty = queue.length === 0;
```
```dart title="queue.dart"
/* Initialize a queue */
// In Dart, Queue is a deque and can also be used as a queue
Queue<int> queue = Queue();
/* Initialize the queue */
// In Dart, the deque class Queue is commonly used as a queue
final Queue<int> queue = Queue();
/* Enqueue elements */
queue.add(1);
@@ -216,43 +216,41 @@ queue.add(5);
queue.add(4);
/* Access the front element */
int peek = queue.first;
final int peek = queue.first;
/* Dequeue an element */
int pop = queue.removeFirst();
final int pop = queue.removeFirst();
/* Get the queue size */
int size = queue.length;
final int size = queue.length;
/* Check whether the queue is empty */
bool isEmpty = queue.isEmpty;
final bool isEmpty = queue.isEmpty;
```
```rust title="queue.rs"
/* Initialize a deque */
// In Rust, use a deque as an ordinary queue
let mut deque: VecDeque<u32> = VecDeque::new();
// Initialize the queue
// In Rust, the deque VecDeque is commonly used as a queue
let mut queue: VecDeque<i32> = VecDeque::new();
/* Enqueue elements */
deque.push_back(1);
deque.push_back(3);
deque.push_back(2);
deque.push_back(5);
deque.push_back(4);
// Enqueue elements
queue.push_back(1);
queue.push_back(3);
queue.push_back(2);
queue.push_back(5);
queue.push_back(4);
/* Access the front element */
if let Some(front) = deque.front() {
}
// Access the front element
let peek = queue.front().unwrap();
/* Dequeue an element */
if let Some(pop) = deque.pop_front() {
}
// Dequeue an element
let pop = queue.pop_front().unwrap();
/* Get the queue size */
let size = deque.len();
// Get the queue size
let size = queue.len();
/* Check whether the queue is empty */
let is_empty = deque.is_empty();
// Check whether the queue is empty
let is_empty = queue.is_empty();
```
```c title="queue.c"
@@ -260,7 +258,7 @@ let is_empty = deque.is_empty();
```
```kotlin title="queue.kt"
/* Initialize a queue */
/* Initialize the queue */
val queue = LinkedList<Int>()
/* Enqueue elements */
@@ -284,8 +282,8 @@ val isEmpty = queue.isEmpty()
```
```ruby title="queue.rb"
# Initialize a queue
# Ruby's built-in Thread::Queue has no peek or traversal methods; use an Array as a queue
# Initialize the queue
# The built-in Ruby queue (Thread::Queue) has no peek or traversal methods; use an Array as a queue
queue = []
# Enqueue elements
@@ -295,11 +293,11 @@ queue.push(2)
queue.push(5)
queue.push(4)
# Access the front element of the queue
# Access a queue element
peek = queue.first
# Dequeue an element
# Note that this is an array, so Array#shift takes O(n) time
# Note that Array#shift has O(n) time complexity because the underlying structure is an array
pop = queue.shift
# Get the queue size

View File

@@ -1,10 +1,10 @@
<!-- [snippet]{stack_operations} -->
```python title="stack.py"
# Initialize a stack
# Python has no built-in stack class; use a list as a stack
# Initialize the stack
# Python has no built-in stack class; a list can be used as a stack
stack: list[int] = []
# Push elements
# Push elements onto the stack
stack.append(1)
stack.append(3)
stack.append(2)
@@ -14,21 +14,21 @@ stack.append(4)
# Access the top element
peek: int = stack[-1]
# Pop an element
# Pop an element from the stack
pop: int = stack.pop()
# Get the stack size
size: int = len(stack)
# Check whether the stack is empty
# Check whether it is empty
is_empty: bool = len(stack) == 0
```
```cpp title="stack.cpp"
/* Initialize a stack */
/* Initialize the stack */
stack<int> stack;
/* Push elements */
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
@@ -38,21 +38,21 @@ stack.push(4);
/* Access the top element */
int top = stack.top();
/* Pop an element */
/* Pop an element from the stack */
stack.pop(); // No return value
/* Get the stack size */
int size = stack.size();
/* Check whether the stack is empty */
/* Check whether it is empty */
bool empty = stack.empty();
```
```java title="stack.java"
/* Initialize a stack */
/* Initialize the stack */
Stack<Integer> stack = new Stack<>();
/* Push elements */
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
@@ -62,21 +62,21 @@ stack.push(4);
/* Access the top element */
int peek = stack.peek();
/* Pop an element */
/* Pop an element from the stack */
int pop = stack.pop();
/* Get the stack size */
int size = stack.size();
/* Check whether the stack is empty */
/* Check whether it is empty */
boolean isEmpty = stack.isEmpty();
```
```csharp title="stack.cs"
/* Initialize a stack */
/* Initialize the stack */
Stack<int> stack = new();
/* Push elements */
/* Push elements onto the stack */
stack.Push(1);
stack.Push(3);
stack.Push(2);
@@ -86,22 +86,22 @@ stack.Push(4);
/* Access the top element */
int peek = stack.Peek();
/* Pop an element */
/* Pop an element from the stack */
int pop = stack.Pop();
/* Get the stack size */
int size = stack.Count;
/* Check whether the stack is empty */
/* Check whether it is empty */
bool isEmpty = stack.Count == 0;
```
```go title="stack_test.go"
/* Initialize a stack */
// In Go, a slice is recommended for use as a stack
/* Initialize the stack */
// In Go, a slice is the recommended way to implement a stack
var stack []int
/* Push elements */
/* Push elements onto the stack */
stack = append(stack, 1)
stack = append(stack, 3)
stack = append(stack, 2)
@@ -111,23 +111,23 @@ stack = append(stack, 4)
/* Access the top element */
peek := stack[len(stack)-1]
/* Pop an element */
/* Pop an element from the stack */
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]
/* Get the stack size */
size := len(stack)
/* Check whether the stack is empty */
/* Check whether it is empty */
isEmpty := len(stack) == 0
```
```swift title="stack.swift"
/* Initialize a stack */
// Swift has no built-in stack class; use an Array as a stack
/* Initialize the stack */
// The Swift standard library has no built-in stack class; Array can be used as a stack
var stack: [Int] = []
/* Push elements */
/* Push elements onto the stack */
stack.append(1)
stack.append(3)
stack.append(2)
@@ -137,47 +137,22 @@ stack.append(4)
/* Access the top element */
let peek = stack.last!
/* Pop an element */
/* Pop an element from the stack */
let pop = stack.removeLast()
/* Get the stack size */
let size = stack.count
/* Check whether the stack is empty */
/* Check whether it is empty */
let isEmpty = stack.isEmpty
```
```javascript title="stack.js"
/* Initialize a stack */
// JavaScript has no built-in stack class; use an Array as a stack
/* Initialize the stack */
// JavaScript has no built-in stack class; an Array can be used as a stack
const stack = [];
/* Push elements */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
/* Access the top element */
const peek = stack[stack.length-1];
/* Pop an element */
const pop = stack.pop();
/* Get the stack size */
const size = stack.length;
/* Check whether the stack is empty */
const is_empty = stack.length === 0;
```
```typescript title="stack.ts"
/* Initialize a stack */
// TypeScript has no built-in stack class; use an Array as a stack
const stack: number[] = [];
/* Push elements */
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
@@ -187,47 +162,22 @@ stack.push(4);
/* Access the top element */
const peek = stack[stack.length - 1];
/* Pop an element */
/* Pop an element from the stack */
const pop = stack.pop();
/* Get the stack size */
const size = stack.length;
/* Check whether the stack is empty */
const is_empty = stack.length === 0;
/* Check whether it is empty */
const isEmpty = stack.length === 0;
```
```dart title="stack.dart"
/* Initialize a stack */
// Dart has no built-in stack class; use a List as a stack
List<int> stack = [];
```typescript title="stack.ts"
/* Initialize the stack */
// TypeScript has no built-in stack class; an Array can be used as a stack
const stack: number[] = [];
/* Push elements */
stack.add(1);
stack.add(3);
stack.add(2);
stack.add(5);
stack.add(4);
/* Access the top element */
int peek = stack.last;
/* Pop an element */
int pop = stack.removeLast();
/* Get the stack size */
int size = stack.length;
/* Check whether the stack is empty */
bool isEmpty = stack.isEmpty;
```
```rust title="stack.rs"
/* Initialize a stack */
// Use a Vec as a stack
let mut stack: Vec<i32> = Vec::new();
/* Push elements */
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
@@ -235,15 +185,65 @@ stack.push(5);
stack.push(4);
/* Access the top element */
let top = stack.last().unwrap();
const peek = stack[stack.length - 1];
/* Pop an element */
let pop = stack.pop().unwrap();
/* Pop an element from the stack */
const pop = stack.pop();
/* Get the stack size */
const size = stack.length;
/* Check whether it is empty */
const isEmpty = stack.length === 0;
```
```dart title="stack.dart"
/* Initialize the stack */
// Dart has no built-in stack class; a List can be used as a stack
final List<int> stack = [];
/* Push elements onto the stack */
stack.add(1);
stack.add(3);
stack.add(2);
stack.add(5);
stack.add(4);
/* Access the top element */
final int peek = stack.last;
/* Pop an element from the stack */
final int pop = stack.removeLast();
/* Get the stack size */
final int size = stack.length;
/* Check whether it is empty */
final bool isEmpty = stack.isEmpty;
```
```rust title="stack.rs"
// Initialize the stack
// In Rust, Vec is the recommended type for implementing a stack
let mut stack: Vec<i32> = Vec::new();
// Push elements onto the stack
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
// Access the top element
let peek = stack.last().unwrap();
// Pop an element from the stack
let pop = stack.pop().unwrap();
// Get the stack size
let size = stack.len();
/* Check whether the stack is empty */
// Check whether the stack is empty
let is_empty = stack.is_empty();
```
@@ -252,10 +252,10 @@ let is_empty = stack.is_empty();
```
```kotlin title="stack.kt"
/* Initialize a stack */
/* Initialize the stack */
val stack = Stack<Int>()
/* Push elements */
/* Push elements onto the stack */
stack.push(1)
stack.push(3)
stack.push(2)
@@ -265,22 +265,22 @@ stack.push(4)
/* Access the top element */
val peek = stack.peek()
/* Pop an element */
/* Pop an element from the stack */
val pop = stack.pop()
/* Get the stack size */
val size = stack.size
/* Check whether the stack is empty */
/* Check whether it is empty */
val isEmpty = stack.isEmpty()
```
```ruby title="stack.rb"
# Initialize a stack
# Initialize the stack
# Ruby has no built-in stack class; use an Array as a stack
stack = []
# Push elements
# Push elements onto the stack
stack << 1
stack << 3
stack << 2
@@ -290,13 +290,13 @@ stack << 4
# Access the top element
peek = stack.last
# Pop an element
# Pop an element from the stack
pop = stack.pop
# Get the stack size
size = stack.length
# Check whether the stack is empty
# Check whether it is empty
is_empty = stack.empty?
```

View File

@@ -133,7 +133,6 @@ impl TreeNode {
/* Binary tree node struct */
typedef struct TreeNode {
int val; // Node value
int height; // Node height
struct TreeNode *left; // Left child pointer
struct TreeNode *right; // Right child pointer
} TreeNode;
@@ -144,7 +143,6 @@ TreeNode *newTreeNode(int val) {
node = (TreeNode *)malloc(sizeof(TreeNode));
node->val = val;
node->height = 0;
node->left = NULL;
node->right = NULL;
return node;
@@ -174,14 +172,14 @@ end
<!-- [snippet]{init_binary_tree} -->
```python title="binary_tree.py"
# Initialize a binary tree
# Initialize nodes
# Initialize the binary tree
# Initialize the nodes
n1 = TreeNode(val=1)
n2 = TreeNode(val=2)
n3 = TreeNode(val=3)
n4 = TreeNode(val=4)
n5 = TreeNode(val=5)
# Connect nodes with references (pointers)
# Set up references (pointers) between the nodes
n1.left = n2
n1.right = n3
n2.left = n4
@@ -189,14 +187,14 @@ n2.right = n5
```
```cpp title="binary_tree.cpp"
/* Initialize a binary tree */
// Initialize nodes
TreeNode* n1 = new TreeNode(1);
TreeNode* n2 = new TreeNode(2);
TreeNode* n3 = new TreeNode(3);
TreeNode* n4 = new TreeNode(4);
TreeNode* n5 = new TreeNode(5);
// Connect nodes with references (pointers)
/* Initialize the binary tree */
// Initialize the nodes
TreeNode *n1 = new TreeNode(1);
TreeNode *n2 = new TreeNode(2);
TreeNode *n3 = new TreeNode(3);
TreeNode *n4 = new TreeNode(4);
TreeNode *n5 = new TreeNode(5);
// Set up references (pointers) between the nodes
n1->left = n2;
n1->right = n3;
n2->left = n4;
@@ -204,13 +202,14 @@ n2->right = n5;
```
```java title="binary_tree.java"
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// Connect nodes with references (pointers)
// Set up references (pointers) between the nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
@@ -218,14 +217,14 @@ n2.right = n5;
```
```csharp title="binary_tree.cs"
/* Initialize a binary tree */
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
TreeNode n1 = new(1);
TreeNode n2 = new(2);
TreeNode n3 = new(3);
TreeNode n4 = new(4);
TreeNode n5 = new(5);
// Connect nodes with references (pointers)
// Set up references (pointers) between the nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
@@ -233,14 +232,14 @@ n2.right = n5;
```
```go title="binary_tree.go"
/* Initialize a binary tree */
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
n1 := NewTreeNode(1)
n2 := NewTreeNode(2)
n3 := NewTreeNode(3)
n4 := NewTreeNode(4)
n5 := NewTreeNode(5)
// Connect nodes with references (pointers)
// Set up references (pointers) between the nodes
n1.Left = n2
n1.Right = n3
n2.Left = n4
@@ -248,13 +247,14 @@ n2.Right = n5
```
```swift title="binary_tree.swift"
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
let n1 = TreeNode(x: 1)
let n2 = TreeNode(x: 2)
let n3 = TreeNode(x: 3)
let n4 = TreeNode(x: 4)
let n5 = TreeNode(x: 5)
// Connect nodes with references (pointers)
// Set up references (pointers) between the nodes
n1.left = n2
n1.right = n3
n2.left = n4
@@ -262,14 +262,14 @@ n2.right = n5
```
```javascript title="binary_tree.js"
/* Initialize a binary tree */
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
let n1 = new TreeNode(1),
n2 = new TreeNode(2),
n3 = new TreeNode(3),
n4 = new TreeNode(4),
n5 = new TreeNode(5);
// Connect nodes with references (pointers)
// Set up references (pointers) between the nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
@@ -277,14 +277,14 @@ n2.right = n5;
```
```typescript title="binary_tree.ts"
/* Initialize a binary tree */
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
let n1 = new TreeNode(1),
n2 = new TreeNode(2),
n3 = new TreeNode(3),
n4 = new TreeNode(4),
n5 = new TreeNode(5);
// Connect nodes with references (pointers)
// Set up references (pointers) between the nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
@@ -292,14 +292,14 @@ n2.right = n5;
```
```dart title="binary_tree.dart"
/* Initialize a binary tree */
// Initialize nodes
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// Connect nodes with references (pointers)
/* Initialize the binary tree */
// Initialize the nodes
TreeNode n1 = TreeNode(1);
TreeNode n2 = TreeNode(2);
TreeNode n3 = TreeNode(3);
TreeNode n4 = TreeNode(4);
TreeNode n5 = TreeNode(5);
// Set up references (pointers) between the nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
@@ -307,28 +307,29 @@ n2.right = n5;
```
```rust title="binary_tree.rs"
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
let n1 = TreeNode::new(1);
let n2 = TreeNode::new(2);
let n3 = TreeNode::new(3);
let n4 = TreeNode::new(4);
let n5 = TreeNode::new(5);
// Connect nodes with references (pointers)
n1.borrow_mut().left = Some(n2.clone());
n1.borrow_mut().right = Some(n3);
n2.borrow_mut().left = Some(n4);
n2.borrow_mut().right = Some(n5);
// Set up references (pointers) between the nodes
n1.borrow_mut().left = Some(Rc::clone(&n2));
n1.borrow_mut().right = Some(Rc::clone(&n3));
n2.borrow_mut().left = Some(Rc::clone(&n4));
n2.borrow_mut().right = Some(Rc::clone(&n5));
```
```c title="binary_tree.c"
/* Initialize a binary tree */
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
TreeNode *n1 = newTreeNode(1);
TreeNode *n2 = newTreeNode(2);
TreeNode *n3 = newTreeNode(3);
TreeNode *n4 = newTreeNode(4);
TreeNode *n5 = newTreeNode(5);
// Connect nodes with references (pointers)
// Set up references (pointers) between the nodes
n1->left = n2;
n1->right = n3;
n2->left = n4;
@@ -336,13 +337,14 @@ n2->right = n5;
```
```kotlin title="binary_tree.kt"
// Initialize nodes
/* Initialize the binary tree */
// Initialize the nodes
val n1 = TreeNode(1)
val n2 = TreeNode(2)
val n3 = TreeNode(3)
val n4 = TreeNode(4)
val n5 = TreeNode(5)
// Connect nodes with references (pointers)
// Set up references (pointers) between the nodes
n1.left = n2
n1.right = n3
n2.left = n4
@@ -350,14 +352,14 @@ n2.right = n5
```
```ruby title="binary_tree.rb"
# Initialize a binary tree
# Initialize nodes
# Initialize the binary tree
# Initialize the nodes
n1 = TreeNode.new(1)
n2 = TreeNode.new(2)
n3 = TreeNode.new(3)
n4 = TreeNode.new(4)
n5 = TreeNode.new(5)
# Connect nodes with references (pointers)
# Set up references (pointers) between the nodes
n1.left = n2
n1.right = n3
n2.left = n4
@@ -369,134 +371,138 @@ https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%2
<!-- [snippet]{insert_remove_node} -->
```python title="binary_tree.py"
# Insert and delete a node
p = TreeNode(0)
# Insert node P between n1 and n2
n1.left = p
p.left = n2
# Delete node P
# Insert and remove nodes
P = TreeNode(0)
# Insert node P between n1 and n2 in n1 -> n2
n1.left = P
P.left = n2
# Remove node P
n1.left = n2
```
```cpp title="binary_tree.cpp"
/* Insert and delete a node */
TreeNode* P = new TreeNode(0);
// Insert node P between n1 and n2
/* Insert and remove nodes */
TreeNode *P = new TreeNode(0);
// Insert node P between n1 and n2 in n1 -> n2
n1->left = P;
P->left = n2;
// Delete node P
// Remove node P
n1->left = n2;
// Free the memory
delete P;
delete P; // Free memory
```
```java title="binary_tree.java"
/* Insert and remove nodes */
TreeNode P = new TreeNode(0);
// Insert node P between n1 and n2
// Insert node P between n1 and n2 in n1 -> n2
n1.left = P;
P.left = n2;
// Delete node P
// Remove node P
n1.left = n2;
```
```csharp title="binary_tree.cs"
/* Insert and delete a node */
/* Insert and remove nodes */
TreeNode P = new(0);
// Insert node P between n1 and n2
// Insert node P between n1 and n2 in n1 -> n2
n1.left = P;
P.left = n2;
// Delete node P
// Remove node P
n1.left = n2;
```
```go title="binary_tree.go"
/* Insert and delete a node */
// Insert node P between n1 and n2
/* Insert and remove nodes */
// Insert node P between n1 and n2 in n1 -> n2
p := NewTreeNode(0)
n1.Left = p
p.Left = n2
// Delete node P
// Remove node P
n1.Left = n2
```
```swift title="binary_tree.swift"
/* Insert and remove nodes */
let P = TreeNode(x: 0)
// Insert node P between n1 and n2
// Insert node P between n1 and n2 in n1 -> n2
n1.left = P
P.left = n2
// Delete node P
// Remove node P
n1.left = n2
```
```javascript title="binary_tree.js"
/* Insert and delete a node */
let P = new TreeNode(0);
// Insert node P between n1 and n2
/* Insert and remove nodes */
const P = new TreeNode(0);
// Insert node P between n1 and n2 in n1 -> n2
n1.left = P;
P.left = n2;
// Delete node P
// Remove node P
n1.left = n2;
```
```typescript title="binary_tree.ts"
/* Insert and delete a node */
/* Insert and remove nodes */
const P = new TreeNode(0);
// Insert node P between n1 and n2
// Insert node P between n1 and n2 in n1 -> n2
n1.left = P;
P.left = n2;
// Delete node P
// Remove node P
n1.left = n2;
```
```dart title="binary_tree.dart"
/* Insert and delete a node */
TreeNode P = new TreeNode(0);
// Insert node P between n1 and n2
n1.left = P;
P.left = n2;
// Delete node P
/* Insert and remove nodes */
TreeNode p = TreeNode(0);
// Insert node P between n1 and n2 in n1 -> n2
n1.left = p;
p.left = n2;
// Remove node P
n1.left = n2;
```
```rust title="binary_tree.rs"
/* Insert and remove nodes */
let p = TreeNode::new(0);
// Insert node P between n1 and n2
n1.borrow_mut().left = Some(p.clone());
p.borrow_mut().left = Some(n2.clone());
// Delete node p
n1.borrow_mut().left = Some(n2);
// Insert node P between n1 and n2 in n1 -> n2
p.borrow_mut().left = Some(Rc::clone(&n2));
n1.borrow_mut().left = Some(Rc::clone(&p));
// Remove node P
drop(p);
n1.borrow_mut().left = Some(Rc::clone(&n2));
```
```c title="binary_tree.c"
/* Insert and delete a node */
/* Insert and remove nodes */
TreeNode *P = newTreeNode(0);
// Insert node P between n1 and n2
// Insert node P between n1 and n2 in n1 -> n2
n1->left = P;
P->left = n2;
// Delete node P
// Remove node P
n1->left = n2;
// Free the memory
// Free memory
free(P);
```
```kotlin title="binary_tree.kt"
/* Insert and remove nodes */
val P = TreeNode(0)
// Insert node P between n1 and n2
// Insert node P between n1 and n2 in n1 -> n2
n1.left = P
P.left = n2
// Delete node P
// Remove node P
n1.left = n2
```
```ruby title="binary_tree.rb"
# Insert and delete a node
# Insert and remove nodes
_p = TreeNode.new(0)
# Insert node _p between n1 and n2
n1.left = _p
_p.left = n2
# Delete the node
# Remove a node
n1.left = n2
```
<!-- [tutor]{insert_remove_node_tutor} -->
https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22Binary%20tree%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20Left%20child%20reference%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20Right%20child%20reference%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20binary%20tree%0A%20%20%20%20%23%20Initialize%20nodes%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20Connect%20nodes%20with%20references%20%28pointers%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20Insert%20and%20delete%20a%20node%0A%20%20%20%20p%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20Insert%20node%20P%20between%20n1%20and%20n2%0A%20%20%20%20n1.left%20%3D%20p%0A%20%20%20%20p.left%20%3D%20n2%0A%20%20%20%20%23%20Delete%20node%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false
https://pythontutor.com/render.html#code=class%20TreeNode%3A%0A%20%20%20%20%22%22%22Binary%20tree%20node%20class%22%22%22%0A%20%20%20%20def%20__init__%28self%2C%20val%3A%20int%29%3A%0A%20%20%20%20%20%20%20%20self.val%3A%20int%20%3D%20val%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%23%20Node%20value%0A%20%20%20%20%20%20%20%20self.left%3A%20TreeNode%20%7C%20None%20%3D%20None%20%20%23%20Left%20child%20reference%0A%20%20%20%20%20%20%20%20self.right%3A%20TreeNode%20%7C%20None%20%3D%20None%20%23%20Right%20child%20reference%0A%0A%22%22%22Driver%20Code%22%22%22%0Aif%20__name__%20%3D%3D%20%22__main__%22%3A%0A%20%20%20%20%23%20Initialize%20a%20binary%20tree%0A%20%20%20%20%23%20Initialize%20nodes%0A%20%20%20%20n1%20%3D%20TreeNode%28val%3D1%29%0A%20%20%20%20n2%20%3D%20TreeNode%28val%3D2%29%0A%20%20%20%20n3%20%3D%20TreeNode%28val%3D3%29%0A%20%20%20%20n4%20%3D%20TreeNode%28val%3D4%29%0A%20%20%20%20n5%20%3D%20TreeNode%28val%3D5%29%0A%20%20%20%20%23%20Connect%20nodes%20with%20references%20%28pointers%29%0A%20%20%20%20n1.left%20%3D%20n2%0A%20%20%20%20n1.right%20%3D%20n3%0A%20%20%20%20n2.left%20%3D%20n4%0A%20%20%20%20n2.right%20%3D%20n5%0A%0A%20%20%20%20%23%20Insert%20and%20delete%20a%20node%0A%20%20%20%20P%20%3D%20TreeNode%280%29%0A%20%20%20%20%23%20Insert%20node%20P%20between%20n1%20and%20n2%0A%20%20%20%20n1.left%20%3D%20P%0A%20%20%20%20P.left%20%3D%20n2%0A%20%20%20%20%23%20Delete%20node%20P%0A%20%20%20%20n1.left%20%3D%20n2&cumulative=false&curInstr=37&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=311&rawInputLstJSON=%5B%5D&textReferences=false

View File

@@ -12,15 +12,15 @@ enum BuiltInHash {
static func main() {
let num = 3
let hashNum = num.hashValue
print("Hash value of integer \(num): \(hashNum)")
print("Integer \(num) has hash value \(hashNum)")
let bol = true
let hashBol = bol.hashValue
print("Hash value of Boolean \(bol): \(hashBol)")
print("Boolean \(bol) has hash value \(hashBol)")
let dec = 3.14159
let hashDec = dec.hashValue
print("Hash value of floating-point number \(dec): \(hashDec)")
print("Floating-point number \(dec) has hash value \(hashDec)")
let str = "Hello 算法"
let hashStr = str.hashValue
@@ -32,6 +32,6 @@ enum BuiltInHash {
let obj = ListNode(x: 0)
let hashObj = obj.hashValue
print("Hash value of node object \(obj): \(hashObj)")
print("Node object \(obj) has hash value \(hashObj)")
}
}

View File

@@ -107,7 +107,7 @@ enum _ArrayQueue {
for i in 0 ..< 10 {
queue.push(num: i)
queue.pop()
print("After enqueueing and dequeueing in round \(i), queue = \(queue.toArray())")
print("After round \(i) of enqueue + dequeue, queue = \(queue.toArray())")
}
}
}

View File

@@ -27,7 +27,7 @@ enum Deque {
print("Rear element peekLast = \(peekLast)")
/* Dequeue an element */
// When using Array as a deque, removing the first element takes O(n) time
// When using Array to simulate a deque, removeFirst has O(n) complexity
let popFirst = deque.removeFirst()
print("Element dequeued from the front, popFirst = \(popFirst); after dequeueing, deque = \(deque)")
let popLast = deque.removeLast()

View File

@@ -25,7 +25,7 @@ enum Queue {
print("Front element peek = \(peek)")
/* Dequeue an element */
// When using Array as a queue, dequeueing takes O(n) time
// When using Array as a queue, removeFirst has O(n) time complexity
let pop = queue.removeFirst()
print("Dequeued element pop = \(pop); after dequeueing, queue = \(queue)")

View File

@@ -103,7 +103,7 @@ console.log('Is the queue empty = ' + isEmpty);
for (let i = 0; i < 10; i++) {
queue.push(i);
queue.pop();
console.log('Round ' + i + ' : after enqueue + dequeue, queue =', queue.toArray());
console.log('After round ' + i + ' of enqueue + dequeue, queue =', queue.toArray());
}
export {};

View File

@@ -6,8 +6,8 @@
/* Doubly linked list node */
class ListNode {
prev: ListNode; // Reference (pointer) to the previous node
next: ListNode; // Reference (pointer) to the next node
prev: ListNode | null; // Reference (pointer) to the previous node
next: ListNode | null; // Reference (pointer) to the next node
val: number; // Node value
constructor(val: number) {

View File

@@ -75,7 +75,7 @@ int main() {
/* 配列を初期化する */
int size = 5;
int arr[5];
int arr[5] = {0};
printf("配列 arr = ");
printArray(arr, size);

View File

@@ -182,7 +182,7 @@ int main() {
int peekFirstNum = peekFirst(deque);
printf("キューの先頭要素 peekFirst = %d\r\n", peekFirstNum);
int peekLastNum = peekLast(deque);
printf("キューの先頭要素 peekLast = %d\r\n", peekLastNum);
printf("キューの末尾要素 peekLast = %d\r\n", peekLastNum);
/* 要素をエンキューする */
pushLast(deque, 4);

View File

@@ -14,7 +14,7 @@ extern "C" {
/* 連結リストのノードの構造体 */
typedef struct ListNode {
int val; // ノードの値
struct ListNode *next; // 次のノードへの参照
struct ListNode *next; // 次のノードへのポインタ
} ListNode;
/* コンストラクタ:新しいノードを初期化する */

View File

@@ -18,7 +18,7 @@ int randomAccess(int *nums, int size) {
/* 配列の長さを拡張する */
int *extend(int *nums, int size, int enlarge) {
// 拡張後の長さの配列を初期化する
int *res = new int[size + enlarge];
int *res = new int[size + enlarge]{};
// 元の配列の全要素を新しい配列にコピーする
for (int i = 0; i < size; i++) {
res[i] = nums[i];
@@ -69,7 +69,7 @@ int find(int *nums, int size, int target) {
int main() {
/* 配列を初期化する */
int size = 5;
int *arr = new int[size];
int *arr = new int[size]{};
cout << "配列 arr = ";
printArray(arr, size);

View File

@@ -36,6 +36,5 @@ void main() {
print("\nキー Key だけを走査する");
map.keys.forEach((key) => print(key));
print("\n値 Value だけを走査する");
map.forEach((key, value) => print("$value"));
map.values.forEach((value) => print(value));
}

View File

@@ -91,8 +91,6 @@ func TestMyHeap(t *testing.T) {
}
func TestTopKHeap(t *testing.T) {
/* ヒープを初期化する */
// 最大ヒープを初期化する
nums := []int{1, 7, 6, 3, 2}
k := 3
res := topKHeap(nums, k)

View File

@@ -51,7 +51,6 @@ func TestDeque(t *testing.T) {
func TestArrayDeque(t *testing.T) {
/* 両端キューを初期化する */
// Go では list を両端キューとして使う
deque := newArrayDeque(16)
/* 要素をエンキューする */
@@ -102,7 +101,7 @@ func TestLinkedListDeque(t *testing.T) {
deque.pushLast(4)
deque.pushFirst(3)
deque.pushFirst(1)
fmt.Print("キュー deque = ")
fmt.Print("両端キュー deque = ")
PrintList(deque.toList())
// キューの先頭要素にアクセス

View File

@@ -84,7 +84,7 @@ func TestArrayQueue(t *testing.T) {
for i := 0; i < 10; i++ {
queue.push(i)
queue.pop()
fmt.Print("第", i, "回のエンキューとデキューの後 queue =")
fmt.Print("第 ", i, " 回のエンキューとデキューの後 queue =")
PrintSlice(queue.toSlice())
}
}

View File

@@ -11,7 +11,7 @@ import java.util.*;
public class list {
public static void main(String[] args) {
/* リストを初期化する */
// 配列の要素型には int[] のラッパークラス Integer[] を使うことに注意
// リストの要素には int のラッパークラス Integer しか使えないため、配列の型は int[] ではなく Integer[] にする必要があることに注意
Integer[] numbers = new Integer[] { 1, 3, 2, 5, 4 };
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
System.out.println("リスト nums = " + nums);

View File

@@ -30,7 +30,7 @@ if __name__ == "__main__":
tup = (12836, "小哈")
hash_tup = hash(tup)
print(f"タプル {tup} のハッシュ値は {hash(hash_tup)}")
print(f"タプル {tup} のハッシュ値は {hash_tup}")
obj = ListNode(0)
hash_obj = hash(obj)

View File

@@ -24,9 +24,9 @@ if __FILE__ == $0
hash_str = str.hash
puts "文字列 #{str} のハッシュ値は #{hash_str}"
tup = [12836, '小哈']
hash_tup = tup.hash
puts "タプル #{tup} のハッシュ値は #{hash_tup}"
arr = [12836, '小哈']
hash_arr = arr.hash
puts "配列 #{arr} のハッシュ値は #{hash_arr}"
obj = ListNode.new(0)
hash_obj = obj.hash

View File

@@ -127,13 +127,13 @@ if __FILE__ == $0
deque.push_last(4)
puts "要素 4 を末尾にエンキューした後 deque = #{deque.to_array}"
deque.push_first(1)
puts "要素 1 を末尾にエンキューした後 deque = #{deque.to_array}"
puts "要素 1 を先頭にエンキューした後 deque = #{deque.to_array}"
# 要素をデキューする
pop_last = deque.pop_last
puts "末尾からデキューした要素 = #{pop_last}、末尾からデキューした後 deque = #{deque.to_array}"
pop_first = deque.pop_first
puts "末尾からデキューした要素 = #{pop_first}、末尾からデキューした後 deque = #{deque.to_array}"
puts "先頭からデキューした要素 = #{pop_first}、先頭からデキューした後 deque = #{deque.to_array}"
# 両端キューの長さを取得する
size = deque.size

View File

@@ -30,7 +30,7 @@ if __FILE__ == $0
pop_front = deque.shift
puts "先頭からデキューした要素 pop_front = #{pop_front}、先頭からデキューした後 deque = #{deque}"
pop_back = deque.pop
puts "末尾からデキューした要素 pop_back = #{pop_back}, 末尾からデキューした後 deque = #{deque}"
puts "末尾からデキューした要素 pop_back = #{pop_back}、末尾からデキューした後 deque = #{deque}"
# 両端キューの長さを取得する
size = deque.length

View File

@@ -4,7 +4,7 @@ Created Time: 2024-04-06
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 双方向連結リストのノード
### 双方向連結リストのノード ###
class ListNode
attr_accessor :val
attr_accessor :next # 後続ノードへの参照
@@ -101,7 +101,7 @@ class LinkedListDeque
pop(true)
end
### 先頭からデキューする ###
### 末尾からデキューする ###
def pop_last
pop(false)
end
@@ -145,7 +145,7 @@ if __FILE__ == $0
peek_first = deque.peek_first
puts "キューの先頭要素 peek_first = #{peek_first}"
peek_last = deque.peek_last
puts "キューの先頭要素 peek_last = #{peek_last}"
puts "キューの末尾要素 peek_last = #{peek_last}"
# 要素をエンキューする
deque.push_last(4)
@@ -155,7 +155,7 @@ if __FILE__ == $0
# 要素をデキューする
pop_last = deque.pop_last
puts "末尾からデキューした要素 = #{pop_last}, 末尾からデキューした後 deque = #{deque.to_array}"
puts "末尾からデキューした要素 = #{pop_last}、末尾からデキューした後 deque = #{deque.to_array}"
pop_first = deque.pop_first
puts "先頭からデキューした要素 = #{pop_first}、先頭からデキューした後 deque = #{deque.to_array}"

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