Cite demo-source regions from doc snippets (pilot) (#2034)

Doc snippets for init_linked_list, init_binary_tree, stack_operations and
five list.md entries now reference marked regions of the demo programs
instead of copying code, so the book shows code that is compiled and run.

- Mark regions in the zh demo files and add the snippet comments that the
  demos lacked, reusing texts that already have reviewed translations.
- Sync ru by hand, regenerate en/ja/ko from the reviewed dictionaries and
  derive zh-hant with OpenCC.
- Convert 97 snippet blocks in six editions to [file]{..}-[region]{..}
  references; init_list and the Rust stack block stay literal until their
  comments have reviewed translations.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Yudong Jin
2026-11-16 03:36:04 +08:00
committed by GitHub
parent 8c96e2f30c
commit 849b6a95b9
318 changed files with 4149 additions and 5691 deletions

View File

@@ -50,7 +50,8 @@ int find(ListNode *head, int target) {
/* Driver Code */
int main() {
/* 初始化链表 */
// [region]{init_linked_list}
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
ListNode *n0 = newListNode(1);
ListNode *n1 = newListNode(3);
@@ -62,6 +63,7 @@ int main() {
n1->next = n2;
n2->next = n3;
n3->next = n4;
// [endregion]{init_linked_list}
printf("初始化的链表为\r\n");
printLinkedList(n0);

View File

@@ -8,6 +8,7 @@
/* Driver Code */
int main() {
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
TreeNode *n1 = newTreeNode(1);
@@ -20,6 +21,7 @@ int main() {
n1->right = n3;
n2->left = n4;
n2->right = n5;
// [endregion]{init_binary_tree}
printf("初始化二叉树\n");
printTree(n1);

View File

@@ -49,7 +49,8 @@ int find(ListNode *head, int target) {
/* Driver Code */
int main() {
/* 初始化链表 */
// [region]{init_linked_list}
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
ListNode *n0 = new ListNode(1);
ListNode *n1 = new ListNode(3);
@@ -61,6 +62,7 @@ int main() {
n1->next = n2;
n2->next = n3;
n3->next = n4;
// [endregion]{init_linked_list}
cout << "初始化的链表为" << endl;
printLinkedList(n0);

View File

@@ -13,58 +13,78 @@ int main() {
cout << "列表 nums = ";
printVector(nums);
// [region]{access_element}
/* 访问元素 */
int num = nums[1];
int num = nums[1]; // 访问索引 1 处的元素
// [endregion]{access_element}
cout << "访问索引 1 处的元素,得到 num = " << num << endl;
// [region]{update_element}
/* 更新元素 */
nums[1] = 0;
nums[1] = 0; // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
cout << "将索引 1 处的元素更新为 0 ,得到 nums = ";
printVector(nums);
// [region]{clear_list}
/* 清空列表 */
nums.clear();
// [endregion]{clear_list}
cout << "清空列表后 nums = ";
printVector(nums);
// [region]{append_element}
/* 在尾部添加元素 */
nums.push_back(1);
nums.push_back(3);
nums.push_back(2);
nums.push_back(5);
nums.push_back(4);
// [endregion]{append_element}
cout << "添加元素后 nums = ";
printVector(nums);
// [region]{insert_element}
/* 在中间插入元素 */
nums.insert(nums.begin() + 3, 6);
nums.insert(nums.begin() + 3, 6); // 在索引 3 处插入数字 6
// [endregion]{insert_element}
cout << "在索引 3 处插入数字 6 ,得到 nums = ";
printVector(nums);
// [region]{remove_element}
/* 删除元素 */
nums.erase(nums.begin() + 3);
nums.erase(nums.begin() + 3); // 删除索引 3 处的元素
// [endregion]{remove_element}
cout << "删除索引 3 处的元素,得到 nums = ";
printVector(nums);
// [region]{iterate_list}
/* 通过索引遍历列表 */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
for (int x : nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* 拼接两个列表 */
vector<int> nums1 = {6, 8, 7, 10, 9};
// 将列表 nums1 拼接到 nums 之后
nums.insert(nums.end(), nums1.begin(), nums1.end());
// [endregion]{concat_list}
cout << "将列表 nums1 拼接到 nums 之后,得到 nums = ";
printVector(nums);
// [region]{sort_list}
/* 排序列表 */
sort(nums.begin(), nums.end());
sort(nums.begin(), nums.end()); // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
cout << "排序列表后 nums = ";
printVector(nums);

View File

@@ -8,33 +8,45 @@
/* Driver Code */
int main() {
// [region]{init_stack}
/* 初始化栈 */
stack<int> stack;
// [endregion]{init_stack}
// [region]{push}
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
// [endregion]{push}
cout << "栈 stack = ";
printStack(stack);
// [region]{peek}
/* 访问栈顶元素 */
int top = stack.top();
// [endregion]{peek}
cout << "栈顶元素 top = " << top << endl;
// [region]{pop}
/* 元素出栈 */
stack.pop(); // 无返回值
// [endregion]{pop}
cout << "出栈元素 pop = " << top << ",出栈后 stack = ";
printStack(stack);
// [region]{size}
/* 获取栈的长度 */
int size = stack.size();
// [endregion]{size}
cout << "栈的长度 size = " << size << endl;
// [region]{is_empty}
/* 判断是否为空 */
bool empty = stack.empty();
// [endregion]{is_empty}
cout << "栈是否为空 = " << empty << endl;
return 0;

View File

@@ -8,6 +8,7 @@
/* Driver Code */
int main() {
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
TreeNode *n1 = new TreeNode(1);
@@ -20,6 +21,7 @@ int main() {
n1->right = n3;
n2->left = n4;
n2->right = n5;
// [endregion]{init_binary_tree}
cout << endl << "初始化二叉树\n" << endl;
printTree(n1);

View File

@@ -47,8 +47,9 @@ public class linked_list {
[Test]
public void Test() {
// 初始化链表
// 初始化各个节点
// [region]{init_linked_list}
// 初始化链表 1 -> 3 -> 2 -> 5 -> 4
// 初始化各个节点
ListNode n0 = new(1);
ListNode n1 = new(3);
ListNode n2 = new(2);
@@ -59,6 +60,7 @@ public class linked_list {
n1.next = n2;
n2.next = n3;
n3.next = n4;
// [endregion]{init_linked_list}
Console.WriteLine($"初始化的链表为{n0}");
// 插入节点

View File

@@ -15,52 +15,71 @@ public class list {
List<int> nums = [.. numbers];
Console.WriteLine("列表 nums = " + string.Join(",", nums));
// [region]{access_element}
/* 访问元素 */
int num = nums[1];
int num = nums[1]; // 访问索引 1 处的元素
// [endregion]{access_element}
Console.WriteLine("访问索引 1 处的元素,得到 num = " + num);
// [region]{update_element}
/* 更新元素 */
nums[1] = 0;
nums[1] = 0; // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
Console.WriteLine("将索引 1 处的元素更新为 0 ,得到 nums = " + string.Join(",", nums));
// [region]{clear_list}
/* 清空列表 */
nums.Clear();
// [endregion]{clear_list}
Console.WriteLine("清空列表后 nums = " + string.Join(",", nums));
// [region]{append_element}
/* 在尾部添加元素 */
nums.Add(1);
nums.Add(3);
nums.Add(2);
nums.Add(5);
nums.Add(4);
// [endregion]{append_element}
Console.WriteLine("添加元素后 nums = " + string.Join(",", nums));
// [region]{insert_element}
/* 在中间插入元素 */
nums.Insert(3, 6);
nums.Insert(3, 6); // 在索引 3 处插入数字 6
// [endregion]{insert_element}
Console.WriteLine("在索引 3 处插入数字 6 ,得到 nums = " + string.Join(",", nums));
// [region]{remove_element}
/* 删除元素 */
nums.RemoveAt(3);
nums.RemoveAt(3); // 删除索引 3 处的元素
// [endregion]{remove_element}
Console.WriteLine("删除索引 3 处的元素,得到 nums = " + string.Join(",", nums));
// [region]{iterate_list}
/* 通过索引遍历列表 */
int count = 0;
for (int i = 0; i < nums.Count; i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
foreach (int x in nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* 拼接两个列表 */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1);
nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后
// [endregion]{concat_list}
Console.WriteLine("将列表 nums1 拼接到 nums 之后,得到 nums = " + string.Join(",", nums));
// [region]{sort_list}
/* 排序列表 */
nums.Sort(); // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
Console.WriteLine("排序列表后 nums = " + string.Join(",", nums));
}
}

View File

@@ -9,9 +9,12 @@ namespace hello_algo.chapter_stack_and_queue;
public class stack {
[Test]
public void Test() {
// [region]{init_stack}
/* 初始化栈 */
Stack<int> stack = new();
// [endregion]{init_stack}
// [region]{push}
/* 元素入栈 */
stack.Push(1);
stack.Push(3);
@@ -19,22 +22,31 @@ public class stack {
stack.Push(5);
stack.Push(4);
// 请注意,stack.ToArray() 得到的是倒序序列,即索引 0 为栈顶
// [endregion]{push}
Console.WriteLine("栈 stack = " + string.Join(",", stack));
// [region]{peek}
/* 访问栈顶元素 */
int peek = stack.Peek();
// [endregion]{peek}
Console.WriteLine("栈顶元素 peek = " + peek);
// [region]{pop}
/* 元素出栈 */
int pop = stack.Pop();
// [endregion]{pop}
Console.WriteLine("出栈元素 pop = " + pop + ",出栈后 stack = " + string.Join(",", stack));
// [region]{size}
/* 获取栈的长度 */
int size = stack.Count;
// [endregion]{size}
Console.WriteLine("栈的长度 size = " + size);
// [region]{is_empty}
/* 判断是否为空 */
bool isEmpty = stack.Count == 0;
// [endregion]{is_empty}
Console.WriteLine("栈是否为空 = " + isEmpty);
}
}

View File

@@ -9,6 +9,7 @@ namespace hello_algo.chapter_tree;
public class binary_tree {
[Test]
public void Test() {
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
TreeNode n1 = new(1);
@@ -21,6 +22,7 @@ public class binary_tree {
n1.right = n3;
n2.left = n4;
n2.right = n5;
// [endregion]{init_binary_tree}
Console.WriteLine("\n初始化二叉树\n");
PrintUtil.PrintTree(n1);

View File

@@ -47,7 +47,8 @@ int find(ListNode? head, int target) {
/* Driver Code */
void main() {
// 初始化链表
// [region]{init_linked_list}
// 初始化链表 1 -> 3 -> 2 -> 5 -> 4
// 初始化各个节点
ListNode n0 = ListNode(1);
ListNode n1 = ListNode(3);
@@ -59,6 +60,7 @@ void main() {
n1.next = n2;
n2.next = n3;
n3.next = n4;
// [endregion]{init_linked_list}
print('初始化的链表为');
printLinkedList(n0);

View File

@@ -12,51 +12,70 @@ void main() {
List<int> nums = [1, 3, 2, 5, 4];
print('列表 nums = $nums');
// [region]{access_element}
/* 访问元素 */
int _num = nums[1];
int _num = nums[1]; // 访问索引 1 处的元素
// [endregion]{access_element}
print('访问索引 1 处的元素,得到 _num = $_num');
// [region]{update_element}
/* 更新元素 */
nums[1] = 0;
nums[1] = 0; // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
print('将索引 1 处的元素更新为 0 ,得到 nums = $nums');
// [region]{clear_list}
/* 清空列表 */
nums.clear();
// [endregion]{clear_list}
print('清空列表后 nums = $nums');
// [region]{append_element}
/* 在尾部添加元素 */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
// [endregion]{append_element}
print('添加元素后 nums = $nums');
// [region]{insert_element}
/* 在中间插入元素 */
nums.insert(3, 6);
nums.insert(3, 6); // 在索引 3 处插入数字 6
// [endregion]{insert_element}
print('在索引 3 处插入数字 6 ,得到 nums = $nums');
// [region]{remove_element}
/* 删除元素 */
nums.removeAt(3);
nums.removeAt(3); // 删除索引 3 处的元素
// [endregion]{remove_element}
print('删除索引 3 处的元素,得到 nums = $nums');
// [region]{iterate_list}
/* 通过索引遍历列表 */
int count = 0;
for (var i = 0; i < nums.length; i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
for (var x in nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* 拼接两个列表 */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.addAll(nums1);
nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后
// [endregion]{concat_list}
print('将列表 nums1 拼接到 nums 之后,得到 nums = $nums');
// [region]{sort_list}
/* 排序列表 */
nums.sort();
nums.sort(); // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
print('排序列表后 nums = $nums');
}

View File

@@ -5,31 +5,43 @@
*/
void main() {
// [region]{init_stack}
/* 初始化栈 */
// Dart 没有内置的栈类,可以把 List 当作栈来使用
final List<int> stack = [];
// [endregion]{init_stack}
// [region]{push}
/* 元素入栈 */
stack.add(1);
stack.add(3);
stack.add(2);
stack.add(5);
stack.add(4);
// [endregion]{push}
print("栈 stack = $stack");
// [region]{peek}
/* 访问栈顶元素 */
final int peek = stack.last;
// [endregion]{peek}
print("栈顶元素 peek = $peek");
// [region]{pop}
/* 元素出栈 */
final int pop = stack.removeLast();
// [endregion]{pop}
print("出栈元素 pop = $pop ,出栈后 stack = $stack");
// [region]{size}
/* 获取栈的长度 */
final int size = stack.length;
// [endregion]{size}
print("栈的长度 size = $size");
// [region]{is_empty}
/* 判断是否为空 */
final bool isEmpty = stack.isEmpty;
// [endregion]{is_empty}
print("栈是否为空 = $isEmpty");
}

View File

@@ -8,8 +8,9 @@ import '../utils/print_util.dart';
import '../utils/tree_node.dart';
void main() {
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 舒适化节点
// 初始化节点
TreeNode n1 = TreeNode(1);
TreeNode n2 = TreeNode(2);
TreeNode n3 = TreeNode(3);
@@ -20,6 +21,7 @@ void main() {
n1.right = n3;
n2.left = n4;
n2.right = n5;
// [endregion]{init_binary_tree}
print("\n初始化二叉树\n");
printTree(n1);

View File

@@ -12,6 +12,7 @@ import (
)
func TestLinkedList(t *testing.T) {
// [region]{init_linked_list}
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
n0 := NewListNode(1)
@@ -25,6 +26,7 @@ func TestLinkedList(t *testing.T) {
n1.Next = n2
n2.Next = n3
n3.Next = n4
// [endregion]{init_linked_list}
fmt.Println("初始化的链表为")
PrintLinkedList(n0)

View File

@@ -16,51 +16,70 @@ func TestList(t *testing.T) {
nums := []int{1, 3, 2, 5, 4}
fmt.Println("列表 nums =", nums)
// [region]{access_element}
/* 访问元素 */
num := nums[1] // 访问索引 1 处的元素
// [endregion]{access_element}
fmt.Println("访问索引 1 处的元素,得到 num =", num)
// [region]{update_element}
/* 更新元素 */
nums[1] = 0 // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
fmt.Println("将索引 1 处的元素更新为 0 ,得到 nums =", nums)
// [region]{clear_list}
/* 清空列表 */
nums = nil
// [endregion]{clear_list}
fmt.Println("清空列表后 nums =", nums)
// [region]{append_element}
/* 在尾部添加元素 */
nums = append(nums, 1)
nums = append(nums, 3)
nums = append(nums, 2)
nums = append(nums, 5)
nums = append(nums, 4)
// [endregion]{append_element}
fmt.Println("添加元素后 nums =", nums)
// [region]{insert_element}
/* 在中间插入元素 */
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 在索引 3 处插入数字 6
// [endregion]{insert_element}
fmt.Println("在索引 3 处插入数字 6 ,得到 nums =", nums)
// [region]{remove_element}
/* 删除元素 */
nums = append(nums[:3], nums[4:]...) // 删除索引 3 处的元素
// [endregion]{remove_element}
fmt.Println("删除索引 3 处的元素,得到 nums =", nums)
// [region]{iterate_list}
/* 通过索引遍历列表 */
count := 0
for i := 0; i < len(nums); i++ {
count += nums[i]
}
/* 直接遍历列表元素 */
count = 0
for _, x := range nums {
count += x
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* 拼接两个列表 */
nums1 := []int{6, 8, 7, 10, 9}
nums = append(nums, nums1...) // 将列表 nums1 拼接到 nums 之后
// [endregion]{concat_list}
fmt.Println("将列表 nums1 拼接到 nums 之后,得到 nums =", nums)
// [region]{sort_list}
/* 排序列表 */
sort.Ints(nums) // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
fmt.Println("排序列表后 nums =", nums)
}

View File

@@ -12,35 +12,47 @@ import (
)
func TestStack(t *testing.T) {
// [region]{init_stack}
/* 初始化栈 */
// 在 Go 中,推荐将 Slice 当作栈来使用
var stack []int
// [endregion]{init_stack}
// [region]{push}
/* 元素入栈 */
stack = append(stack, 1)
stack = append(stack, 3)
stack = append(stack, 2)
stack = append(stack, 5)
stack = append(stack, 4)
// [endregion]{push}
fmt.Print("栈 stack = ")
PrintSlice(stack)
// [region]{peek}
/* 访问栈顶元素 */
peek := stack[len(stack)-1]
// [endregion]{peek}
fmt.Println("栈顶元素 peek =", peek)
// [region]{pop}
/* 元素出栈 */
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// [endregion]{pop}
fmt.Print("出栈元素 pop = ", pop, ",出栈后 stack = ")
PrintSlice(stack)
// [region]{size}
/* 获取栈的长度 */
size := len(stack)
// [endregion]{size}
fmt.Println("栈的长度 size =", size)
// [region]{is_empty}
/* 判断是否为空 */
isEmpty := len(stack) == 0
// [endregion]{is_empty}
fmt.Println("栈是否为空 =", isEmpty)
}

View File

@@ -12,6 +12,7 @@ import (
)
func TestBinaryTree(t *testing.T) {
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
n1 := NewTreeNode(1)
@@ -24,6 +25,7 @@ func TestBinaryTree(t *testing.T) {
n1.Right = n3
n2.Left = n4
n2.Right = n5
// [endregion]{init_binary_tree}
fmt.Println("初始化二叉树")
PrintTree(n1)

View File

@@ -50,7 +50,8 @@ public class linked_list {
/* Driver Code */
public static void main(String[] args) {
/* 初始化链表 */
// [region]{init_linked_list}
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
ListNode n0 = new ListNode(1);
ListNode n1 = new ListNode(3);
@@ -62,6 +63,7 @@ public class linked_list {
n1.next = n2;
n2.next = n3;
n3.next = n4;
// [endregion]{init_linked_list}
System.out.println("初始化的链表为");
PrintUtil.printLinkedList(n0);

View File

@@ -16,51 +16,70 @@ public class list {
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
System.out.println("列表 nums = " + nums);
// [region]{access_element}
/* 访问元素 */
int num = nums.get(1);
int num = nums.get(1); // 访问索引 1 处的元素
// [endregion]{access_element}
System.out.println("访问索引 1 处的元素,得到 num = " + num);
// [region]{update_element}
/* 更新元素 */
nums.set(1, 0);
nums.set(1, 0); // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
System.out.println("将索引 1 处的元素更新为 0 ,得到 nums = " + nums);
// [region]{clear_list}
/* 清空列表 */
nums.clear();
// [endregion]{clear_list}
System.out.println("清空列表后 nums = " + nums);
// [region]{append_element}
/* 在尾部添加元素 */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
// [endregion]{append_element}
System.out.println("添加元素后 nums = " + nums);
// [region]{insert_element}
/* 在中间插入元素 */
nums.add(3, 6);
nums.add(3, 6); // 在索引 3 处插入数字 6
// [endregion]{insert_element}
System.out.println("在索引 3 处插入数字 6 ,得到 nums = " + nums);
// [region]{remove_element}
/* 删除元素 */
nums.remove(3);
nums.remove(3); // 删除索引 3 处的元素
// [endregion]{remove_element}
System.out.println("删除索引 3 处的元素,得到 nums = " + nums);
// [region]{iterate_list}
/* 通过索引遍历列表 */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums.get(i);
}
/* 直接遍历列表元素 */
for (int x : nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* 拼接两个列表 */
List<Integer> nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 }));
nums.addAll(nums1);
nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后
// [endregion]{concat_list}
System.out.println("将列表 nums1 拼接到 nums 之后,得到 nums = " + nums);
// [region]{sort_list}
/* 排序列表 */
Collections.sort(nums);
Collections.sort(nums); // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
System.out.println("排序列表后 nums = " + nums);
}
}

View File

@@ -10,31 +10,43 @@ import java.util.*;
public class stack {
public static void main(String[] args) {
// [region]{init_stack}
/* 初始化栈 */
Stack<Integer> stack = new Stack<>();
// [endregion]{init_stack}
// [region]{push}
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
// [endregion]{push}
System.out.println("栈 stack = " + stack);
// [region]{peek}
/* 访问栈顶元素 */
int peek = stack.peek();
// [endregion]{peek}
System.out.println("栈顶元素 peek = " + peek);
// [region]{pop}
/* 元素出栈 */
int pop = stack.pop();
// [endregion]{pop}
System.out.println("出栈元素 pop = " + pop + ",出栈后 stack = " + stack);
// [region]{size}
/* 获取栈的长度 */
int size = stack.size();
// [endregion]{size}
System.out.println("栈的长度 size = " + size);
// [region]{is_empty}
/* 判断是否为空 */
boolean isEmpty = stack.isEmpty();
// [endregion]{is_empty}
System.out.println("栈是否为空 = " + isEmpty);
}
}

View File

@@ -10,6 +10,7 @@ import utils.*;
public class binary_tree {
public static void main(String[] args) {
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
TreeNode n1 = new TreeNode(1);
@@ -22,6 +23,7 @@ public class binary_tree {
n1.right = n3;
n2.left = n4;
n2.right = n5;
// [endregion]{init_binary_tree}
System.out.println("\n初始化二叉树\n");
PrintUtil.printTree(n1);

View File

@@ -48,7 +48,8 @@ function find(head, target) {
}
/* Driver Code */
/* 初始化链表 */
// [region]{init_linked_list}
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
const n0 = new ListNode(1);
const n1 = new ListNode(3);
@@ -60,6 +61,7 @@ n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
// [endregion]{init_linked_list}
console.log('初始化的链表为');
printLinkedList(n0);

View File

@@ -8,50 +8,69 @@
const nums = [1, 3, 2, 5, 4];
console.log(`列表 nums = ${nums}`);
// [region]{access_element}
/* 访问元素 */
const num = nums[1];
const num = nums[1]; // 访问索引 1 处的元素
// [endregion]{access_element}
console.log(`访问索引 1 处的元素,得到 num = ${num}`);
// [region]{update_element}
/* 更新元素 */
nums[1] = 0;
nums[1] = 0; // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
console.log(`将索引 1 处的元素更新为 0 ,得到 nums = ${nums}`);
// [region]{clear_list}
/* 清空列表 */
nums.length = 0;
// [endregion]{clear_list}
console.log(`清空列表后 nums = ${nums}`);
// [region]{append_element}
/* 在尾部添加元素 */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
// [endregion]{append_element}
console.log(`添加元素后 nums = ${nums}`);
// [region]{insert_element}
/* 在中间插入元素 */
nums.splice(3, 0, 6);
nums.splice(3, 0, 6); // 在索引 3 处插入数字 6
// [endregion]{insert_element}
console.log(`在索引 3 处插入数字 6 ,得到 nums = ${nums}`);
// [region]{remove_element}
/* 删除元素 */
nums.splice(3, 1);
nums.splice(3, 1); // 删除索引 3 处的元素
// [endregion]{remove_element}
console.log(`删除索引 3 处的元素,得到 nums = ${nums}`);
// [region]{iterate_list}
/* 通过索引遍历列表 */
let count = 0;
for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
for (const x of nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* 拼接两个列表 */
const nums1 = [6, 8, 7, 10, 9];
nums.push(...nums1);
nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后
// [endregion]{concat_list}
console.log(`将列表 nums1 拼接到 nums 之后,得到 nums = ${nums}`);
// [region]{sort_list}
/* 排序列表 */
nums.sort((a, b) => a - b);
nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
console.log(`排序列表后 nums = ${nums}`);

View File

@@ -5,31 +5,43 @@
*/
/* Driver Code */
// [region]{init_stack}
/* 初始化栈 */
// JavaScript 没有内置的栈类,可以把 Array 当作栈来使用
const stack = [];
// [endregion]{init_stack}
// [region]{push}
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
// [endregion]{push}
console.log('栈 stack =', stack);
// [region]{peek}
/* 访问栈顶元素 */
const peek = stack[stack.length - 1];
// [endregion]{peek}
console.log('栈顶元素 peek =', peek);
// [region]{pop}
/* 元素出栈 */
const pop = stack.pop();
// [endregion]{pop}
console.log('出栈元素 pop =', pop);
console.log('出栈后 stack =', stack);
// [region]{size}
/* 获取栈的长度 */
const size = stack.length;
// [endregion]{size}
console.log('栈的长度 size =', size);
// [region]{is_empty}
/* 判断是否为空 */
const isEmpty = stack.length === 0;
// [endregion]{is_empty}
console.log('栈是否为空 =', isEmpty);

View File

@@ -7,6 +7,7 @@
const { TreeNode } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
let n1 = new TreeNode(1),
@@ -19,6 +20,7 @@ n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
// [endregion]{init_binary_tree}
console.log('\n初始化二叉树\n');
printTree(n1);

View File

@@ -52,7 +52,8 @@ fun find(head: ListNode?, target: Int): Int {
/* Driver Code */
fun main() {
/* 初始化链表 */
// [region]{init_linked_list}
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
val n0 = ListNode(1)
val n1 = ListNode(3)
@@ -65,6 +66,7 @@ fun main() {
n1.next = n2
n2.next = n3
n3.next = n4
// [endregion]{init_linked_list}
println("初始化的链表为")
printLinkedList(n0)

View File

@@ -13,34 +13,47 @@ fun main() {
val nums = mutableListOf(1, 3, 2, 5, 4)
println("列表 nums = $nums")
// [region]{access_element}
/* 访问元素 */
val num = nums[1]
val num = nums[1] // 访问索引 1 处的元素
// [endregion]{access_element}
println("访问索引 1 处的元素,得到 num = $num")
// [region]{update_element}
/* 更新元素 */
nums[1] = 0
nums[1] = 0 // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
println("将索引 1 处的元素更新为 0 ,得到 nums = $nums")
// [region]{clear_list}
/* 清空列表 */
nums.clear()
// [endregion]{clear_list}
println("清空列表后 nums = $nums")
// [region]{append_element}
/* 在尾部添加元素 */
nums.add(1)
nums.add(3)
nums.add(2)
nums.add(5)
nums.add(4)
// [endregion]{append_element}
println("添加元素后 nums = $nums")
// [region]{insert_element}
/* 在中间插入元素 */
nums.add(3, 6)
nums.add(3, 6) // 在索引 3 处插入数字 6
// [endregion]{insert_element}
println("在索引 3 处插入数字 6 ,得到 nums = $nums")
// [region]{remove_element}
/* 删除元素 */
nums.removeAt(3)
nums.removeAt(3) // 删除索引 3 处的元素
// [endregion]{remove_element}
println("删除索引 3 处的元素,得到 nums = $nums")
// [region]{iterate_list}
/* 通过索引遍历列表 */
var count = 0
for (i in nums.indices) {
@@ -51,13 +64,18 @@ fun main() {
for (j in nums) {
count += j
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* 拼接两个列表*/
val nums1 = mutableListOf(6, 8, 7, 10, 9)
nums.addAll(nums1)
nums.addAll(nums1) // 将列表 nums1 拼接到 nums 之后
// [endregion]{concat_list}
println("将列表 nums1 拼接到 nums 之后,得到 nums = $nums")
// [region]{sort_list}
/* 排序列表 */
nums.sort()
nums.sort() // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
println("排序列表后 nums = $nums")
}

View File

@@ -10,30 +10,42 @@ import java.util.*
/* Driver Code */
fun main() {
// [region]{init_stack}
/* 初始化栈 */
val stack = Stack<Int>()
// [endregion]{init_stack}
// [region]{push}
/* 元素入栈 */
stack.push(1)
stack.push(3)
stack.push(2)
stack.push(5)
stack.push(4)
// [endregion]{push}
println("栈 stack = $stack")
// [region]{peek}
/* 访问栈顶元素 */
val peek = stack.peek()
// [endregion]{peek}
println("栈顶元素 peek = $peek")
// [region]{pop}
/* 元素出栈 */
val pop = stack.pop()
// [endregion]{pop}
println("出栈元素 pop = $pop,出栈后 stack = $stack")
// [region]{size}
/* 获取栈的长度 */
val size = stack.size
// [endregion]{size}
println("栈的长度 size = $size")
// [region]{is_empty}
/* 判断是否为空 */
val isEmpty = stack.isEmpty()
// [endregion]{is_empty}
println("栈是否为空 = $isEmpty")
}

View File

@@ -11,6 +11,7 @@ import utils.printTree
/* Driver Code */
fun main() {
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
val n1 = TreeNode(1)
@@ -23,6 +24,7 @@ fun main() {
n1.right = n3
n2.left = n4
n2.right = n5
// [endregion]{init_binary_tree}
println("\n初始化二叉树\n")
printTree(n1)

View File

@@ -50,7 +50,8 @@ def find(head: ListNode, target: int) -> int:
"""Driver Code"""
if __name__ == "__main__":
# 初始化链表
# [region]{init_linked_list}
# 初始化链表 1 -> 3 -> 2 -> 5 -> 4
# 初始化各个节点
n0 = ListNode(1)
n1 = ListNode(3)
@@ -62,6 +63,7 @@ if __name__ == "__main__":
n1.next = n2
n2.next = n3
n3.next = n4
# [endregion]{init_linked_list}
print("初始化的链表为")
print_linked_list(n0)

View File

@@ -10,47 +10,66 @@ if __name__ == "__main__":
nums: list[int] = [1, 3, 2, 5, 4]
print("\n列表 nums =", nums)
# [region]{access_element}
# 访问元素
x: int = nums[1]
x: int = nums[1] # 访问索引 1 处的元素
# [endregion]{access_element}
print("\n访问索引 1 处的元素,得到 x =", x)
# [region]{update_element}
# 更新元素
nums[1] = 0
nums[1] = 0 # 将索引 1 处的元素更新为 0
# [endregion]{update_element}
print("\n将索引 1 处的元素更新为 0 ,得到 nums =", nums)
# [region]{clear_list}
# 清空列表
nums.clear()
# [endregion]{clear_list}
print("\n清空列表后 nums =", nums)
# [region]{append_element}
# 在尾部添加元素
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
# [endregion]{append_element}
print("\n添加元素后 nums =", nums)
# [region]{insert_element}
# 在中间插入元素
nums.insert(3, 6)
nums.insert(3, 6) # 在索引 3 处插入数字 6
# [endregion]{insert_element}
print("\n在索引 3 处插入数字 6 ,得到 nums =", nums)
# [region]{remove_element}
# 删除元素
nums.pop(3)
nums.pop(3) # 删除索引 3 处的元素
# [endregion]{remove_element}
print("\n删除索引 3 处的元素,得到 nums =", nums)
# [region]{iterate_list}
# 通过索引遍历列表
count = 0
for i in range(len(nums)):
count += nums[i]
# 直接遍历列表元素
for num in nums:
count += num
# [endregion]{iterate_list}
# [region]{concat_list}
# 拼接两个列表
nums1 = [6, 8, 7, 10, 9]
nums += nums1
nums += nums1 # 将列表 nums1 拼接到 nums 之后
# [endregion]{concat_list}
print("\n将列表 nums1 拼接到 nums 之后,得到 nums =", nums)
# [region]{sort_list}
# 排序列表
nums.sort()
nums.sort() # 排序后,列表元素从小到大排列
# [endregion]{sort_list}
print("\n排序列表后 nums =", nums)

View File

@@ -6,31 +6,43 @@ Author: Peng Chen (pengchzn@gmail.com)
"""Driver Code"""
if __name__ == "__main__":
# [region]{init_stack}
# 初始化栈
# Python 没有内置的栈类,可以把 list 当作栈来使用
stack: list[int] = []
# [endregion]{init_stack}
# [region]{push}
# 元素入栈
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)
# [endregion]{push}
print("栈 stack =", stack)
# [region]{peek}
# 访问栈顶元素
peek: int = stack[-1]
# [endregion]{peek}
print("栈顶元素 peek =", peek)
# [region]{pop}
# 元素出栈
pop: int = stack.pop()
# [endregion]{pop}
print("出栈元素 pop =", pop)
print("出栈后 stack =", stack)
# [region]{size}
# 获取栈的长度
size: int = len(stack)
# [endregion]{size}
print("栈的长度 size =", size)
# [region]{is_empty}
# 判断是否为空
is_empty: bool = len(stack) == 0
# [endregion]{is_empty}
print("栈是否为空 =", is_empty)

View File

@@ -13,6 +13,7 @@ from modules import TreeNode, print_tree
"""Driver Code"""
if __name__ == "__main__":
# [region]{init_binary_tree}
# 初始化二叉树
# 初始化节点
n1 = TreeNode(val=1)
@@ -25,6 +26,7 @@ if __name__ == "__main__":
n1.right = n3
n2.left = n4
n2.right = n5
# [endregion]{init_binary_tree}
print("\n初始化二叉树\n")
print_tree(n1)

View File

@@ -49,7 +49,8 @@ end
### Driver Code ###
if __FILE__ == $0
# 初始化链表
# [region]{init_linked_list}
# 初始化链表 1 -> 3 -> 2 -> 5 -> 4
# 初始化各个节点
n0 = ListNode.new(1)
n1 = ListNode.new(3)
@@ -61,6 +62,7 @@ if __FILE__ == $0
n1.next = n2
n2.next = n3
n3.next = n4
# [endregion]{init_linked_list}
puts "初始化的链表为"
print_linked_list(n0)

View File

@@ -10,34 +10,47 @@ if __FILE__ == $0
nums = [1, 3, 2, 5, 4]
puts "列表 nums = #{nums}"
# [region]{access_element}
# 访问元素
num = nums[1]
num = nums[1] # 访问索引 1 处的元素
# [endregion]{access_element}
puts "访问索引 1 处的元素,得到 num = #{num}"
# [region]{update_element}
# 更新元素
nums[1] = 0
nums[1] = 0 # 将索引 1 处的元素更新为 0
# [endregion]{update_element}
puts "将索引 1 处的元素更新为 0 ,得到 nums = #{nums}"
# [region]{clear_list}
# 清空列表
nums.clear
# [endregion]{clear_list}
puts "清空列表后 nums = #{nums}"
# [region]{append_element}
# 在尾部添加元素
nums << 1
nums << 3
nums << 2
nums << 5
nums << 4
# [endregion]{append_element}
puts "添加元素后 nums = #{nums}"
# [region]{insert_element}
# 在中间插入元素
nums.insert(3, 6)
nums.insert(3, 6) # 在索引 3 处插入数字 6
# [endregion]{insert_element}
puts "在索引 3 处插入元素 6 ,得到 nums = #{nums}"
# [region]{remove_element}
# 删除元素
nums.delete_at(3)
nums.delete_at(3) # 删除索引 3 处的元素
# [endregion]{remove_element}
puts "删除索引 3 处的元素,得到 nums = #{nums}"
# [region]{iterate_list}
# 通过索引遍历列表
count = 0
for i in 0...nums.length
@@ -49,12 +62,18 @@ if __FILE__ == $0
nums.each do |x|
count += x
end
# [endregion]{iterate_list}
# [region]{concat_list}
# 拼接两个列表
nums1 = [6, 8, 7, 10, 9]
nums += nums1
# [endregion]{concat_list}
puts "将列表 nums1 拼接到 nums 之后,得到 nums = #{nums}"
nums = nums.sort { |a, b| a <=> b }
# [region]{sort_list}
# 排序列表
nums = nums.sort { |a, b| a <=> b } # 排序后,列表元素从小到大排列
# [endregion]{sort_list}
puts "排序列表后 nums = #{nums}"
end

View File

@@ -6,32 +6,44 @@ Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
### Driver Code ###
if __FILE__ == $0
# [region]{init_stack}
# 初始化栈
# Ruby 没有内置的栈类,可以把 Array 当作栈来使用
stack = []
# [endregion]{init_stack}
# [region]{push}
# 元素入栈
stack << 1
stack << 3
stack << 2
stack << 5
stack << 4
# [endregion]{push}
puts "栈 stack = #{stack}"
# [region]{peek}
# 访问栈顶元素
peek = stack.last
# [endregion]{peek}
puts "栈顶元素 peek = #{peek}"
# [region]{pop}
# 元素出栈
pop = stack.pop
# [endregion]{pop}
puts "出栈元素 pop = #{pop}"
puts "出栈后 stack = #{stack}"
# [region]{size}
# 获取栈的长度
size = stack.length
# [endregion]{size}
puts "栈的长度 size = #{size}"
# [region]{is_empty}
# 判断是否为空
is_empty = stack.empty?
# [endregion]{is_empty}
puts "栈是否为空 = #{is_empty}"
end

View File

@@ -9,6 +9,7 @@ require_relative '../utils/print_util'
### Driver Code ###
if __FILE__ == $0
# [region]{init_binary_tree}
# 初始化二叉树
# 初始化节点
n1 = TreeNode.new(1)
@@ -21,6 +22,7 @@ if __FILE__ == $0
n1.right = n3
n2.left = n4
n2.right = n5
# [endregion]{init_binary_tree}
puts "\n初始化二叉树\n\n"
print_tree(n1)

View File

@@ -65,18 +65,21 @@ pub fn find<T: PartialEq>(head: Rc<RefCell<ListNode<T>>>, target: T) -> i32 {
/* Driver Code */
fn main() {
/* 初始化链表 */
// [region]{init_linked_list}
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
let n0 = ListNode::new(1);
let n1 = ListNode::new(3);
let n2 = ListNode::new(2);
let n3 = ListNode::new(5);
let n4 = ListNode::new(4);
// 构建节点之间的引用
n0.borrow_mut().next = Some(n1.clone());
n1.borrow_mut().next = Some(n2.clone());
n2.borrow_mut().next = Some(n3.clone());
n3.borrow_mut().next = Some(n4.clone());
// [endregion]{init_linked_list}
print!("初始化的链表为 ");
print_util::print_linked_list(&n0);

View File

@@ -12,60 +12,79 @@ fn main() {
print!("列表 nums = ");
print_util::print_array(&nums);
// [region]{access_element}
// 访问元素
let num = nums[1];
let num = nums[1]; // 访问索引 1 处的元素
// [endregion]{access_element}
println!("\n访问索引 1 处的元素,得到 num = {num}");
// [region]{update_element}
// 更新元素
nums[1] = 0;
nums[1] = 0; // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
print!("将索引 1 处的元素更新为 0 ,得到 nums = ");
print_util::print_array(&nums);
// [region]{clear_list}
// 清空列表
nums.clear();
// [endregion]{clear_list}
print!("\n清空列表后 nums = ");
print_util::print_array(&nums);
// [region]{append_element}
// 在尾部添加元素
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
// [endregion]{append_element}
print!("\n添加元素后 nums = ");
print_util::print_array(&nums);
// [region]{insert_element}
// 在中间插入元素
nums.insert(3, 6);
nums.insert(3, 6); // 在索引 3 处插入数字 6
// [endregion]{insert_element}
print!("\n在索引 3 处插入数字 6 ,得到 nums = ");
print_util::print_array(&nums);
// [region]{remove_element}
// 删除元素
nums.remove(3);
nums.remove(3); // 删除索引 3 处的元素
// [endregion]{remove_element}
print!("\n删除索引 3 处的元素,得到 nums = ");
print_util::print_array(&nums);
// [region]{iterate_list}
// 通过索引遍历列表
let mut _count = 0;
for i in 0..nums.len() {
_count += nums[i];
}
// 直接遍历列表元素
_count = 0;
for x in &nums {
_count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
// 拼接两个列表
let mut nums1 = vec![6, 8, 7, 10, 9];
nums.append(&mut nums1); // append(移动) 之后 nums1 为空!
// [endregion]{concat_list}
// nums.extend(&nums1); // extend(借用) nums1 能继续使用
print!("\n将列表 nums1 拼接到 nums 之后,得到 nums = ");
print_util::print_array(&nums);
// [region]{sort_list}
// 排序列表
nums.sort();
nums.sort(); // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
print!("\n排序列表后 nums = ");
print_util::print_array(&nums);
}

View File

@@ -8,6 +8,7 @@ use hello_algo_rust::include::{print_util, TreeNode};
/* Driver Code */
fn main() {
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
let n1 = TreeNode::new(1);
@@ -20,6 +21,7 @@ fn main() {
n1.borrow_mut().right = Some(Rc::clone(&n3));
n2.borrow_mut().left = Some(Rc::clone(&n4));
n2.borrow_mut().right = Some(Rc::clone(&n5));
// [endregion]{init_binary_tree}
println!("\n初始化二叉树\n");
print_util::print_tree(&n1);

View File

@@ -144,199 +144,55 @@ end
<!-- [snippet]{init_linked_list} -->
```python title="linked_list.py"
# 初始化链表 1 -> 3 -> 2 -> 5 -> 4
# 初始化各个节点
n0 = ListNode(1)
n1 = ListNode(3)
n2 = ListNode(2)
n3 = ListNode(5)
n4 = ListNode(4)
# 构建节点之间的引用
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
[file]{linked_list}-[region]{init_linked_list}
```
```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);
// 构建节点之间的引用
n0->next = n1;
n1->next = n2;
n2->next = n3;
n3->next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```java title="linked_list.java"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
ListNode n0 = new ListNode(1);
ListNode n1 = new ListNode(3);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(5);
ListNode n4 = new ListNode(4);
// 构建节点之间的引用
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```csharp title="linked_list.cs"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
ListNode n0 = new(1);
ListNode n1 = new(3);
ListNode n2 = new(2);
ListNode n3 = new(5);
ListNode n4 = new(4);
// 构建节点之间的引用
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```go title="linked_list.go"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
n0 := NewListNode(1)
n1 := NewListNode(3)
n2 := NewListNode(2)
n3 := NewListNode(5)
n4 := NewListNode(4)
// 构建节点之间的引用
n0.Next = n1
n1.Next = n2
n2.Next = n3
n3.Next = n4
[file]{linked_list_test}-[region]{init_linked_list}
```
```swift title="linked_list.swift"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
let n0 = ListNode(x: 1)
let n1 = ListNode(x: 3)
let n2 = ListNode(x: 2)
let n3 = ListNode(x: 5)
let n4 = ListNode(x: 4)
// 构建节点之间的引用
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
[file]{linked_list}-[region]{init_linked_list}
```
```javascript title="linked_list.js"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
const n0 = new ListNode(1);
const n1 = new ListNode(3);
const n2 = new ListNode(2);
const n3 = new ListNode(5);
const n4 = new ListNode(4);
// 构建节点之间的引用
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```typescript title="linked_list.ts"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
const n0 = new ListNode(1);
const n1 = new ListNode(3);
const n2 = new ListNode(2);
const n3 = new ListNode(5);
const n4 = new ListNode(4);
// 构建节点之间的引用
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```dart title="linked_list.dart"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
ListNode n0 = ListNode(1);
ListNode n1 = ListNode(3);
ListNode n2 = ListNode(2);
ListNode n3 = ListNode(5);
ListNode n4 = ListNode(4);
// 构建节点之间的引用
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```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 }));
// 构建节点之间的引用
n0.borrow_mut().next = Some(n1.clone());
n1.borrow_mut().next = Some(n2.clone());
n2.borrow_mut().next = Some(n3.clone());
n3.borrow_mut().next = Some(n4.clone());
[file]{linked_list}-[region]{init_linked_list}
```
```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);
// 构建节点之间的引用
n0->next = n1;
n1->next = n2;
n2->next = n3;
n3->next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```kotlin title="linked_list.kt"
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
val n0 = ListNode(1)
val n1 = ListNode(3)
val n2 = ListNode(2)
val n3 = ListNode(5)
val n4 = ListNode(4)
// 构建节点之间的引用
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```ruby title="linked_list.rb"
# 初始化链表 1 -> 3 -> 2 -> 5 -> 4
# 初始化各个节点
n0 = ListNode.new(1)
n1 = ListNode.new(3)
n2 = ListNode.new(2)
n3 = ListNode.new(5)
n4 = ListNode.new(4)
# 构建节点之间的引用
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
[file]{linked_list}-[region]{init_linked_list}
```
<!-- [tutor]{init_linked_list_tutor} -->

View File

@@ -108,82 +108,63 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{access_element} -->
```python title="list.py"
# 访问元素
num: int = nums[1] # 访问索引 1 处的元素
[file]{list}-[region]{access_element}
# 更新元素
nums[1] = 0 # 将索引 1 处的元素更新为 0
[file]{list}-[region]{update_element}
```
```cpp title="list.cpp"
/* 访问元素 */
int num = nums[1]; // 访问索引 1 处的元素
[file]{list}-[region]{access_element}
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
[file]{list}-[region]{update_element}
```
```java title="list.java"
/* 访问元素 */
int num = nums.get(1); // 访问索引 1 处的元素
[file]{list}-[region]{access_element}
/* 更新元素 */
nums.set(1, 0); // 将索引 1 处的元素更新为 0
[file]{list}-[region]{update_element}
```
```csharp title="list.cs"
/* 访问元素 */
int num = nums[1]; // 访问索引 1 处的元素
[file]{list}-[region]{access_element}
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
[file]{list}-[region]{update_element}
```
```go title="list_test.go"
/* 访问元素 */
num := nums[1] // 访问索引 1 处的元素
[file]{list_test}-[region]{access_element}
/* 更新元素 */
nums[1] = 0 // 将索引 1 处的元素更新为 0
[file]{list_test}-[region]{update_element}
```
```swift title="list.swift"
/* 访问元素 */
let num = nums[1] // 访问索引 1 处的元素
[file]{list}-[region]{access_element}
/* 更新元素 */
nums[1] = 0 // 将索引 1 处的元素更新为 0
[file]{list}-[region]{update_element}
```
```javascript title="list.js"
/* 访问元素 */
const num = nums[1]; // 访问索引 1 处的元素
[file]{list}-[region]{access_element}
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
[file]{list}-[region]{update_element}
```
```typescript title="list.ts"
/* 访问元素 */
const num: number = nums[1]; // 访问索引 1 处的元素
[file]{list}-[region]{access_element}
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
[file]{list}-[region]{update_element}
```
```dart title="list.dart"
/* 访问元素 */
int num = nums[1]; // 访问索引 1 处的元素
[file]{list}-[region]{access_element}
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
[file]{list}-[region]{update_element}
```
```rust title="list.rs"
/* 访问元素 */
let num: i32 = nums[1]; // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0; // 将索引 1 处的元素更新为 0
[file]{list}-[region]{access_element}
[file]{list}-[region]{update_element}
```
```c title="list.c"
@@ -191,17 +172,15 @@ nums[1] = 0; // 将索引 1 处的元素更新为 0
```
```kotlin title="list.kt"
/* 访问元素 */
val num = nums[1] // 访问索引 1 处的元素
/* 更新元素 */
nums[1] = 0 // 将索引 1 处的元素更新为 0
[file]{list}-[region]{access_element}
[file]{list}-[region]{update_element}
```
```ruby title="list.rb"
# 访问元素
num = nums[1] # 访问索引 1 处的元素
# 更新元素
nums[1] = 0 # 将索引 1 处的元素更新为 0
[file]{list}-[region]{access_element}
[file]{list}-[region]{update_element}
```
<!-- [tutor]{access_element_tutor} -->
@@ -209,183 +188,103 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{insert_remove_element} -->
```python title="list.py"
# 清空列表
nums.clear()
[file]{list}-[region]{clear_list}
# 在尾部添加元素
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
[file]{list}-[region]{append_element}
# 在中间插入元素
nums.insert(3, 6) # 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
# 删除元素
nums.pop(3) # 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```cpp title="list.cpp"
/* 清空列表 */
nums.clear();
[file]{list}-[region]{clear_list}
/* 在尾部添加元素 */
nums.push_back(1);
nums.push_back(3);
nums.push_back(2);
nums.push_back(5);
nums.push_back(4);
[file]{list}-[region]{append_element}
/* 在中间插入元素 */
nums.insert(nums.begin() + 3, 6); // 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
/* 删除元素 */
nums.erase(nums.begin() + 3); // 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```java title="list.java"
/* 清空列表 */
nums.clear();
[file]{list}-[region]{clear_list}
/* 在尾部添加元素 */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
[file]{list}-[region]{append_element}
/* 在中间插入元素 */
nums.add(3, 6); // 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
/* 删除元素 */
nums.remove(3); // 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```csharp title="list.cs"
/* 清空列表 */
nums.Clear();
[file]{list}-[region]{clear_list}
/* 在尾部添加元素 */
nums.Add(1);
nums.Add(3);
nums.Add(2);
nums.Add(5);
nums.Add(4);
[file]{list}-[region]{append_element}
/* 在中间插入元素 */
nums.Insert(3, 6); // 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
/* 删除元素 */
nums.RemoveAt(3); // 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```go title="list_test.go"
/* 清空列表 */
nums = nil
[file]{list_test}-[region]{clear_list}
/* 在尾部添加元素 */
nums = append(nums, 1)
nums = append(nums, 3)
nums = append(nums, 2)
nums = append(nums, 5)
nums = append(nums, 4)
[file]{list_test}-[region]{append_element}
/* 在中间插入元素 */
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // 在索引 3 处插入数字 6
[file]{list_test}-[region]{insert_element}
/* 删除元素 */
nums = append(nums[:3], nums[4:]...) // 删除索引 3 处的元素
[file]{list_test}-[region]{remove_element}
```
```swift title="list.swift"
/* 清空列表 */
nums.removeAll()
[file]{list}-[region]{clear_list}
/* 在尾部添加元素 */
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
[file]{list}-[region]{append_element}
/* 在中间插入元素 */
nums.insert(6, at: 3) // 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
/* 删除元素 */
nums.remove(at: 3) // 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```javascript title="list.js"
/* 清空列表 */
nums.length = 0;
[file]{list}-[region]{clear_list}
/* 在尾部添加元素 */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
[file]{list}-[region]{append_element}
/* 在中间插入元素 */
nums.splice(3, 0, 6); // 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
/* 删除元素 */
nums.splice(3, 1); // 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```typescript title="list.ts"
/* 清空列表 */
nums.length = 0;
[file]{list}-[region]{clear_list}
/* 在尾部添加元素 */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
[file]{list}-[region]{append_element}
/* 在中间插入元素 */
nums.splice(3, 0, 6); // 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
/* 删除元素 */
nums.splice(3, 1); // 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```dart title="list.dart"
/* 清空列表 */
nums.clear();
[file]{list}-[region]{clear_list}
/* 在尾部添加元素 */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
[file]{list}-[region]{append_element}
/* 在中间插入元素 */
nums.insert(3, 6); // 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
/* 删除元素 */
nums.removeAt(3); // 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```rust title="list.rs"
/* 清空列表 */
nums.clear();
[file]{list}-[region]{clear_list}
/* 在尾部添加元素 */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
[file]{list}-[region]{append_element}
/* 在中间插入元素 */
nums.insert(3, 6); // 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
/* 删除元素 */
nums.remove(3); // 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```c title="list.c"
@@ -393,39 +292,23 @@ nums.remove(3); // 删除索引 3 处的元素
```
```kotlin title="list.kt"
/* 清空列表 */
nums.clear();
[file]{list}-[region]{clear_list}
/* 在尾部添加元素 */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
[file]{list}-[region]{append_element}
/* 在中间插入元素 */
nums.add(3, 6); // 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
/* 删除元素 */
nums.removeAt(3); // 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
```ruby title="list.rb"
# 清空列表
nums.clear
[file]{list}-[region]{clear_list}
# 在尾部添加元素
nums << 1
nums << 3
nums << 2
nums << 5
nums << 4
[file]{list}-[region]{append_element}
# 在中间插入元素
nums.insert(3, 6) # 在索引 3 处插入数字 6
[file]{list}-[region]{insert_element}
# 删除元素
nums.delete_at(3) # 删除索引 3 处的元素
[file]{list}-[region]{remove_element}
```
<!-- [tutor]{insert_remove_element_tutor} -->
@@ -433,139 +316,43 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{iterate_list} -->
```python title="list.py"
# 通过索引遍历列表
count = 0
for i in range(len(nums)):
count += nums[i]
# 直接遍历列表元素
for num in nums:
count += num
[file]{list}-[region]{iterate_list}
```
```cpp title="list.cpp"
/* 通过索引遍历列表 */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
for (int num : nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```java title="list.java"
/* 通过索引遍历列表 */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums.get(i);
}
/* 直接遍历列表元素 */
for (int num : nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```csharp title="list.cs"
/* 通过索引遍历列表 */
int count = 0;
for (int i = 0; i < nums.Count; i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
foreach (int num in nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```go title="list_test.go"
/* 通过索引遍历列表 */
count := 0
for i := 0; i < len(nums); i++ {
count += nums[i]
}
/* 直接遍历列表元素 */
count = 0
for _, num := range nums {
count += num
}
[file]{list_test}-[region]{iterate_list}
```
```swift title="list.swift"
/* 通过索引遍历列表 */
var count = 0
for i in nums.indices {
count += nums[i]
}
/* 直接遍历列表元素 */
count = 0
for num in nums {
count += num
}
[file]{list}-[region]{iterate_list}
```
```javascript title="list.js"
/* 通过索引遍历列表 */
let count = 0;
for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
for (const num of nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```typescript title="list.ts"
/* 通过索引遍历列表 */
let count = 0;
for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
for (const num of nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```dart title="list.dart"
/* 通过索引遍历列表 */
int count = 0;
for (var i = 0; i < nums.length; i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
for (var num in nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```rust title="list.rs"
// 通过索引遍历列表
let mut _count = 0;
for i in 0..nums.len() {
_count += nums[i];
}
// 直接遍历列表元素
_count = 0;
for num in &nums {
_count += num;
}
[file]{list}-[region]{iterate_list}
```
```c title="list.c"
@@ -573,30 +360,11 @@ for num in &nums {
```
```kotlin title="list.kt"
/* 通过索引遍历列表 */
var count = 0
for (i in nums.indices) {
count += nums[i]
}
/* 直接遍历列表元素 */
for (num in nums) {
count += num
}
[file]{list}-[region]{iterate_list}
```
```ruby title="list.rb"
# 通过索引遍历列表
count = 0
for i in 0...nums.length
count += nums[i]
end
# 直接遍历列表元素
count = 0
for num in nums
count += num
end
[file]{list}-[region]{iterate_list}
```
<!-- [tutor]{iterate_list_tutor} -->
@@ -604,64 +372,43 @@ 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]
nums += nums1 # 将列表 nums1 拼接到 nums 之后
[file]{list}-[region]{concat_list}
```
```cpp title="list.cpp"
/* 拼接两个列表 */
vector<int> nums1 = { 6, 8, 7, 10, 9 };
// 将列表 nums1 拼接到 nums 之后
nums.insert(nums.end(), nums1.begin(), nums1.end());
[file]{list}-[region]{concat_list}
```
```java title="list.java"
/* 拼接两个列表 */
List<Integer> nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 }));
nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后
[file]{list}-[region]{concat_list}
```
```csharp title="list.cs"
/* 拼接两个列表 */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1); // 将列表 nums1 拼接到 nums 之后
[file]{list}-[region]{concat_list}
```
```go title="list_test.go"
/* 拼接两个列表 */
nums1 := []int{6, 8, 7, 10, 9}
nums = append(nums, nums1...) // 将列表 nums1 拼接到 nums 之后
[file]{list_test}-[region]{concat_list}
```
```swift title="list.swift"
/* 拼接两个列表 */
let nums1 = [6, 8, 7, 10, 9]
nums.append(contentsOf: nums1) // 将列表 nums1 拼接到 nums 之后
[file]{list}-[region]{concat_list}
```
```javascript title="list.js"
/* 拼接两个列表 */
const nums1 = [6, 8, 7, 10, 9];
nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后
[file]{list}-[region]{concat_list}
```
```typescript title="list.ts"
/* 拼接两个列表 */
const nums1: number[] = [6, 8, 7, 10, 9];
nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后
[file]{list}-[region]{concat_list}
```
```dart title="list.dart"
/* 拼接两个列表 */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.addAll(nums1); // 将列表 nums1 拼接到 nums 之后
[file]{list}-[region]{concat_list}
```
```rust title="list.rs"
/* 拼接两个列表 */
let nums1: Vec<i32> = vec![6, 8, 7, 10, 9];
nums.extend(nums1);
[file]{list}-[region]{concat_list}
```
```c title="list.c"
@@ -669,15 +416,11 @@ nums.extend(nums1);
```
```kotlin title="list.kt"
/* 拼接两个列表 */
val nums1 = intArrayOf(6, 8, 7, 10, 9).toMutableList()
nums.addAll(nums1) // 将列表 nums1 拼接到 nums 之后
[file]{list}-[region]{concat_list}
```
```ruby title="list.rb"
# 拼接两个列表
nums1 = [6, 8, 7, 10, 9]
nums += nums1
[file]{list}-[region]{concat_list}
```
<!-- [tutor]{concat_list_tutor} -->
@@ -685,53 +428,43 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{sort_list} -->
```python title="list.py"
# 排序列表
nums.sort() # 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```cpp title="list.cpp"
/* 排序列表 */
sort(nums.begin(), nums.end()); // 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```java title="list.java"
/* 排序列表 */
Collections.sort(nums); // 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```csharp title="list.cs"
/* 排序列表 */
nums.Sort(); // 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```go title="list_test.go"
/* 排序列表 */
sort.Ints(nums) // 排序后,列表元素从小到大排列
[file]{list_test}-[region]{sort_list}
```
```swift title="list.swift"
/* 排序列表 */
nums.sort() // 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```javascript title="list.js"
/* 排序列表 */
nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```typescript title="list.ts"
/* 排序列表 */
nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```dart title="list.dart"
/* 排序列表 */
nums.sort(); // 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```rust title="list.rs"
/* 排序列表 */
nums.sort(); // 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```c title="list.c"
@@ -739,13 +472,11 @@ nums.sort(); // 排序后,列表元素从小到大排列
```
```kotlin title="list.kt"
/* 排序列表 */
nums.sort() // 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
```ruby title="list.rb"
# 排序列表
nums = nums.sort { |a, b| a <=> b } # 排序后,列表元素从小到大排列
[file]{list}-[region]{sort_list}
```
<!-- [tutor]{sort_list_tutor} -->

View File

@@ -1,225 +1,128 @@
<!-- [snippet]{stack_operations} -->
```python title="stack.py"
# 初始化栈
# Python 没有内置的栈类,可以把 list 当作栈来使用
stack: list[int] = []
[file]{stack}-[region]{init_stack}
# 元素入栈
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)
[file]{stack}-[region]{push}
# 访问栈顶元素
peek: int = stack[-1]
[file]{stack}-[region]{peek}
# 元素出栈
pop: int = stack.pop()
[file]{stack}-[region]{pop}
# 获取栈的长度
size: int = len(stack)
[file]{stack}-[region]{size}
# 判断是否为空
is_empty: bool = len(stack) == 0
[file]{stack}-[region]{is_empty}
```
```cpp title="stack.cpp"
/* 初始化栈 */
stack<int> stack;
[file]{stack}-[region]{init_stack}
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
[file]{stack}-[region]{push}
/* 访问栈顶元素 */
int top = stack.top();
[file]{stack}-[region]{peek}
/* 元素出栈 */
stack.pop(); // 无返回值
[file]{stack}-[region]{pop}
/* 获取栈的长度 */
int size = stack.size();
[file]{stack}-[region]{size}
/* 判断是否为空 */
bool empty = stack.empty();
[file]{stack}-[region]{is_empty}
```
```java title="stack.java"
/* 初始化栈 */
Stack<Integer> stack = new Stack<>();
[file]{stack}-[region]{init_stack}
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
[file]{stack}-[region]{push}
/* 访问栈顶元素 */
int peek = stack.peek();
[file]{stack}-[region]{peek}
/* 元素出栈 */
int pop = stack.pop();
[file]{stack}-[region]{pop}
/* 获取栈的长度 */
int size = stack.size();
[file]{stack}-[region]{size}
/* 判断是否为空 */
boolean isEmpty = stack.isEmpty();
[file]{stack}-[region]{is_empty}
```
```csharp title="stack.cs"
/* 初始化栈 */
Stack<int> stack = new();
[file]{stack}-[region]{init_stack}
/* 元素入栈 */
stack.Push(1);
stack.Push(3);
stack.Push(2);
stack.Push(5);
stack.Push(4);
[file]{stack}-[region]{push}
/* 访问栈顶元素 */
int peek = stack.Peek();
[file]{stack}-[region]{peek}
/* 元素出栈 */
int pop = stack.Pop();
[file]{stack}-[region]{pop}
/* 获取栈的长度 */
int size = stack.Count;
[file]{stack}-[region]{size}
/* 判断是否为空 */
bool isEmpty = stack.Count == 0;
[file]{stack}-[region]{is_empty}
```
```go title="stack_test.go"
/* 初始化栈 */
// 在 Go 中,推荐将 Slice 当作栈来使用
var stack []int
[file]{stack_test}-[region]{init_stack}
/* 元素入栈 */
stack = append(stack, 1)
stack = append(stack, 3)
stack = append(stack, 2)
stack = append(stack, 5)
stack = append(stack, 4)
[file]{stack_test}-[region]{push}
/* 访问栈顶元素 */
peek := stack[len(stack)-1]
[file]{stack_test}-[region]{peek}
/* 元素出栈 */
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]
[file]{stack_test}-[region]{pop}
/* 获取栈的长度 */
size := len(stack)
[file]{stack_test}-[region]{size}
/* 判断是否为空 */
isEmpty := len(stack) == 0
[file]{stack_test}-[region]{is_empty}
```
```swift title="stack.swift"
/* 初始化栈 */
// Swift 没有内置的栈类,可以把 Array 当作栈来使用
var stack: [Int] = []
[file]{stack}-[region]{init_stack}
/* 元素入栈 */
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)
[file]{stack}-[region]{push}
/* 访问栈顶元素 */
let peek = stack.last!
[file]{stack}-[region]{peek}
/* 元素出栈 */
let pop = stack.removeLast()
[file]{stack}-[region]{pop}
/* 获取栈的长度 */
let size = stack.count
[file]{stack}-[region]{size}
/* 判断是否为空 */
let isEmpty = stack.isEmpty
[file]{stack}-[region]{is_empty}
```
```javascript title="stack.js"
/* 初始化栈 */
// JavaScript 没有内置的栈类,可以把 Array 当作栈来使用
const stack = [];
[file]{stack}-[region]{init_stack}
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
[file]{stack}-[region]{push}
/* 访问栈顶元素 */
const peek = stack[stack.length-1];
[file]{stack}-[region]{peek}
/* 元素出栈 */
const pop = stack.pop();
[file]{stack}-[region]{pop}
/* 获取栈的长度 */
const size = stack.length;
[file]{stack}-[region]{size}
/* 判断是否为空 */
const is_empty = stack.length === 0;
[file]{stack}-[region]{is_empty}
```
```typescript title="stack.ts"
/* 初始化栈 */
// TypeScript 没有内置的栈类,可以把 Array 当作栈来使用
const stack: number[] = [];
[file]{stack}-[region]{init_stack}
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
[file]{stack}-[region]{push}
/* 访问栈顶元素 */
const peek = stack[stack.length - 1];
[file]{stack}-[region]{peek}
/* 元素出栈 */
const pop = stack.pop();
[file]{stack}-[region]{pop}
/* 获取栈的长度 */
const size = stack.length;
[file]{stack}-[region]{size}
/* 判断是否为空 */
const is_empty = stack.length === 0;
[file]{stack}-[region]{is_empty}
```
```dart title="stack.dart"
/* 初始化栈 */
// Dart 没有内置的栈类,可以把 List 当作栈来使用
List<int> stack = [];
[file]{stack}-[region]{init_stack}
/* 元素入栈 */
stack.add(1);
stack.add(3);
stack.add(2);
stack.add(5);
stack.add(4);
[file]{stack}-[region]{push}
/* 访问栈顶元素 */
int peek = stack.last;
[file]{stack}-[region]{peek}
/* 元素出栈 */
int pop = stack.removeLast();
[file]{stack}-[region]{pop}
/* 获取栈的长度 */
int size = stack.length;
[file]{stack}-[region]{size}
/* 判断是否为空 */
bool isEmpty = stack.isEmpty;
[file]{stack}-[region]{is_empty}
```
```rust title="stack.rs"
@@ -252,52 +155,31 @@ let is_empty = stack.is_empty();
```
```kotlin title="stack.kt"
/* 初始化栈 */
val stack = Stack<Int>()
[file]{stack}-[region]{init_stack}
/* 元素入栈 */
stack.push(1)
stack.push(3)
stack.push(2)
stack.push(5)
stack.push(4)
[file]{stack}-[region]{push}
/* 访问栈顶元素 */
val peek = stack.peek()
[file]{stack}-[region]{peek}
/* 元素出栈 */
val pop = stack.pop()
[file]{stack}-[region]{pop}
/* 获取栈的长度 */
val size = stack.size
[file]{stack}-[region]{size}
/* 判断是否为空 */
val isEmpty = stack.isEmpty()
[file]{stack}-[region]{is_empty}
```
```ruby title="stack.rb"
# 初始化栈
# Ruby 没有内置的栈类,可以把 Array 当作栈来使用
stack = []
[file]{stack}-[region]{init_stack}
# 元素入栈
stack << 1
stack << 3
stack << 2
stack << 5
stack << 4
[file]{stack}-[region]{push}
# 访问栈顶元素
peek = stack.last
[file]{stack}-[region]{peek}
# 元素出栈
pop = stack.pop
[file]{stack}-[region]{pop}
# 获取栈的长度
size = stack.length
[file]{stack}-[region]{size}
# 判断是否为空
is_empty = stack.empty?
[file]{stack}-[region]{is_empty}
```
<!-- [tutor]{stack_operations_tutor} -->

View File

@@ -174,194 +174,55 @@ end
<!-- [snippet]{init_binary_tree} -->
```python title="binary_tree.py"
# 初始化二叉树
# 初始化节点
n1 = TreeNode(val=1)
n2 = TreeNode(val=2)
n3 = TreeNode(val=3)
n4 = TreeNode(val=4)
n5 = TreeNode(val=5)
# 构建节点之间的引用(指针)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
[file]{binary_tree}-[region]{init_binary_tree}
```
```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);
// 构建节点之间的引用(指针)
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```java title="binary_tree.java"
// 初始化节点
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// 构建节点之间的引用(指针)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```csharp title="binary_tree.cs"
/* 初始化二叉树 */
// 初始化节点
TreeNode n1 = new(1);
TreeNode n2 = new(2);
TreeNode n3 = new(3);
TreeNode n4 = new(4);
TreeNode n5 = new(5);
// 构建节点之间的引用(指针)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```go title="binary_tree.go"
/* 初始化二叉树 */
// 初始化节点
n1 := NewTreeNode(1)
n2 := NewTreeNode(2)
n3 := NewTreeNode(3)
n4 := NewTreeNode(4)
n5 := NewTreeNode(5)
// 构建节点之间的引用(指针)
n1.Left = n2
n1.Right = n3
n2.Left = n4
n2.Right = n5
[file]{binary_tree_test}-[region]{init_binary_tree}
```
```swift title="binary_tree.swift"
// 初始化节点
let n1 = TreeNode(x: 1)
let n2 = TreeNode(x: 2)
let n3 = TreeNode(x: 3)
let n4 = TreeNode(x: 4)
let n5 = TreeNode(x: 5)
// 构建节点之间的引用(指针)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
[file]{binary_tree}-[region]{init_binary_tree}
```
```javascript title="binary_tree.js"
/* 初始化二叉树 */
// 初始化节点
let n1 = new TreeNode(1),
n2 = new TreeNode(2),
n3 = new TreeNode(3),
n4 = new TreeNode(4),
n5 = new TreeNode(5);
// 构建节点之间的引用(指针)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```typescript title="binary_tree.ts"
/* 初始化二叉树 */
// 初始化节点
let n1 = new TreeNode(1),
n2 = new TreeNode(2),
n3 = new TreeNode(3),
n4 = new TreeNode(4),
n5 = new TreeNode(5);
// 构建节点之间的引用(指针)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```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);
// 构建节点之间的引用(指针)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```rust title="binary_tree.rs"
// 初始化节点
let n1 = TreeNode::new(1);
let n2 = TreeNode::new(2);
let n3 = TreeNode::new(3);
let n4 = TreeNode::new(4);
let n5 = TreeNode::new(5);
// 构建节点之间的引用(指针)
n1.borrow_mut().left = Some(n2.clone());
n1.borrow_mut().right = Some(n3);
n2.borrow_mut().left = Some(n4);
n2.borrow_mut().right = Some(n5);
[file]{binary_tree}-[region]{init_binary_tree}
```
```c title="binary_tree.c"
/* 初始化二叉树 */
// 初始化节点
TreeNode *n1 = newTreeNode(1);
TreeNode *n2 = newTreeNode(2);
TreeNode *n3 = newTreeNode(3);
TreeNode *n4 = newTreeNode(4);
TreeNode *n5 = newTreeNode(5);
// 构建节点之间的引用(指针)
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```kotlin title="binary_tree.kt"
// 初始化节点
val n1 = TreeNode(1)
val n2 = TreeNode(2)
val n3 = TreeNode(3)
val n4 = TreeNode(4)
val n5 = TreeNode(5)
// 构建节点之间的引用(指针)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
[file]{binary_tree}-[region]{init_binary_tree}
```
```ruby title="binary_tree.rb"
# 初始化二叉树
# 初始化节点
n1 = TreeNode.new(1)
n2 = TreeNode.new(2)
n3 = TreeNode.new(3)
n4 = TreeNode.new(4)
n5 = TreeNode.new(5)
# 构建节点之间的引用(指针)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
[file]{binary_tree}-[region]{init_binary_tree}
```
<!-- [tutor]{init_binary_tree_tutor} -->

View File

@@ -54,7 +54,8 @@ func find(head: ListNode, target: Int) -> Int {
enum LinkedList {
/* Driver Code */
static func main() {
/* 初始化链表 */
// [region]{init_linked_list}
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
let n0 = ListNode(x: 1)
let n1 = ListNode(x: 3)
@@ -66,6 +67,7 @@ enum LinkedList {
n1.next = n2
n2.next = n3
n3.next = n4
// [endregion]{init_linked_list}
print("初始化的链表为")
PrintUtil.printLinkedList(head: n0)

View File

@@ -12,52 +12,71 @@ enum List {
var nums = [1, 3, 2, 5, 4]
print("列表 nums = \(nums)")
// [region]{access_element}
/* 访问元素 */
let num = nums[1]
let num = nums[1] // 访问索引 1 处的元素
// [endregion]{access_element}
print("访问索引 1 处的元素,得到 num = \(num)")
// [region]{update_element}
/* 更新元素 */
nums[1] = 0
nums[1] = 0 // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
print("将索引 1 处的元素更新为 0 ,得到 nums = \(nums)")
// [region]{clear_list}
/* 清空列表 */
nums.removeAll()
// [endregion]{clear_list}
print("清空列表后 nums = \(nums)")
// [region]{append_element}
/* 在尾部添加元素 */
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
// [endregion]{append_element}
print("添加元素后 nums = \(nums)")
// [region]{insert_element}
/* 在中间插入元素 */
nums.insert(6, at: 3)
nums.insert(6, at: 3) // 在索引 3 处插入数字 6
// [endregion]{insert_element}
print("在索引 3 处插入数字 6 ,得到 nums = \(nums)")
// [region]{remove_element}
/* 删除元素 */
nums.remove(at: 3)
nums.remove(at: 3) // 删除索引 3 处的元素
// [endregion]{remove_element}
print("删除索引 3 处的元素,得到 nums = \(nums)")
// [region]{iterate_list}
/* 通过索引遍历列表 */
var count = 0
for i in nums.indices {
count += nums[i]
}
/* 直接遍历列表元素 */
count = 0
for x in nums {
count += x
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* 拼接两个列表 */
let nums1 = [6, 8, 7, 10, 9]
nums.append(contentsOf: nums1)
nums.append(contentsOf: nums1) // 将列表 nums1 拼接到 nums 之后
// [endregion]{concat_list}
print("将列表 nums1 拼接到 nums 之后,得到 nums = \(nums)")
// [region]{sort_list}
/* 排序列表 */
nums.sort()
nums.sort() // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
print("排序列表后 nums = \(nums)")
}
}

View File

@@ -8,32 +8,44 @@
enum Stack {
/* Driver Code */
static func main() {
// [region]{init_stack}
/* 初始化栈 */
// Swift 没有内置的栈类,可以把 Array 当作栈来使用
var stack: [Int] = []
// [endregion]{init_stack}
// [region]{push}
/* 元素入栈 */
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)
// [endregion]{push}
print("栈 stack = \(stack)")
// [region]{peek}
/* 访问栈顶元素 */
let peek = stack.last!
// [endregion]{peek}
print("栈顶元素 peek = \(peek)")
// [region]{pop}
/* 元素出栈 */
let pop = stack.removeLast()
// [endregion]{pop}
print("出栈元素 pop = \(pop),出栈后 stack = \(stack)")
// [region]{size}
/* 获取栈的长度 */
let size = stack.count
// [endregion]{size}
print("栈的长度 size = \(size)")
// [region]{is_empty}
/* 判断是否为空 */
let isEmpty = stack.isEmpty
// [endregion]{is_empty}
print("栈是否为空 = \(isEmpty)")
}
}

View File

@@ -10,6 +10,7 @@ import utils
enum BinaryTree {
/* Driver Code */
static func main() {
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
let n1 = TreeNode(x: 1)
@@ -22,6 +23,7 @@ enum BinaryTree {
n1.right = n3
n2.left = n4
n2.right = n5
// [endregion]{init_binary_tree}
print("\n初始化二叉树\n")
PrintUtil.printTree(root: n1)

View File

@@ -50,7 +50,8 @@ function find(head: ListNode | null, target: number): number {
}
/* Driver Code */
/* 初始化链表 */
// [region]{init_linked_list}
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
const n0 = new ListNode(1);
const n1 = new ListNode(3);
@@ -62,6 +63,7 @@ n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
// [endregion]{init_linked_list}
console.log('初始化的链表为');
printLinkedList(n0);

View File

@@ -8,52 +8,71 @@
const nums: number[] = [1, 3, 2, 5, 4];
console.log(`列表 nums = ${nums}`);
// [region]{access_element}
/* 访问元素 */
const num: number = nums[1];
const num: number = nums[1]; // 访问索引 1 处的元素
// [endregion]{access_element}
console.log(`访问索引 1 处的元素,得到 num = ${num}`);
// [region]{update_element}
/* 更新元素 */
nums[1] = 0;
nums[1] = 0; // 将索引 1 处的元素更新为 0
// [endregion]{update_element}
console.log(`将索引 1 处的元素更新为 0 ,得到 nums = ${nums}`);
// [region]{clear_list}
/* 清空列表 */
nums.length = 0;
// [endregion]{clear_list}
console.log(`清空列表后 nums = ${nums}`);
// [region]{append_element}
/* 在尾部添加元素 */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
// [endregion]{append_element}
console.log(`添加元素后 nums = ${nums}`);
// [region]{insert_element}
/* 在中间插入元素 */
nums.splice(3, 0, 6);
nums.splice(3, 0, 6); // 在索引 3 处插入数字 6
// [endregion]{insert_element}
console.log(`在索引 3 处插入数字 6 ,得到 nums = ${nums}`);
// [region]{remove_element}
/* 删除元素 */
nums.splice(3, 1);
nums.splice(3, 1); // 删除索引 3 处的元素
// [endregion]{remove_element}
console.log(`删除索引 3 处的元素,得到 nums = ${nums}`);
// [region]{iterate_list}
/* 通过索引遍历列表 */
let count = 0;
for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* 直接遍历列表元素 */
count = 0;
for (const x of nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* 拼接两个列表 */
const nums1: number[] = [6, 8, 7, 10, 9];
nums.push(...nums1);
nums.push(...nums1); // 将列表 nums1 拼接到 nums 之后
// [endregion]{concat_list}
console.log(`将列表 nums1 拼接到 nums 之后,得到 nums = ${nums}`);
// [region]{sort_list}
/* 排序列表 */
nums.sort((a, b) => a - b);
nums.sort((a, b) => a - b); // 排序后,列表元素从小到大排列
// [endregion]{sort_list}
console.log(`排序列表后 nums = ${nums}`);
export {};

View File

@@ -5,33 +5,45 @@
*/
/* Driver Code */
// [region]{init_stack}
/* 初始化栈 */
// TypeScript 没有内置的栈类,可以把 Array 当作栈来使用
const stack: number[] = [];
// [endregion]{init_stack}
// [region]{push}
/* 元素入栈 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
// [endregion]{push}
console.log('栈 stack =', stack);
// [region]{peek}
/* 访问栈顶元素 */
const peek = stack[stack.length - 1];
// [endregion]{peek}
console.log('栈顶元素 peek =', peek);
// [region]{pop}
/* 元素出栈 */
const pop = stack.pop();
// [endregion]{pop}
console.log('出栈元素 pop =', pop);
console.log('出栈后 stack =', stack);
// [region]{size}
/* 获取栈的长度 */
const size = stack.length;
// [endregion]{size}
console.log('栈的长度 size =', size);
// [region]{is_empty}
/* 判断是否为空 */
const isEmpty = stack.length === 0;
// [endregion]{is_empty}
console.log('栈是否为空 =', isEmpty);
export {};

View File

@@ -7,6 +7,7 @@
import { TreeNode } from '../modules/TreeNode';
import { printTree } from '../modules/PrintUtil';
// [region]{init_binary_tree}
/* 初始化二叉树 */
// 初始化节点
let n1 = new TreeNode(1),
@@ -19,6 +20,7 @@ n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
// [endregion]{init_binary_tree}
console.log('\n初始化二叉树\n');
printTree(n1);

View File

@@ -50,7 +50,8 @@ int find(ListNode *head, int target) {
/* Driver code */
int main() {
/* Initialize the linked list */
// [region]{init_linked_list}
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the individual nodes
ListNode *n0 = newListNode(1);
ListNode *n1 = newListNode(3);
@@ -62,6 +63,7 @@ int main() {
n1->next = n2;
n2->next = n3;
n3->next = n4;
// [endregion]{init_linked_list}
printf("Initial linked list:\r\n");
printLinkedList(n0);

View File

@@ -8,6 +8,7 @@
/* Driver code */
int main() {
// [region]{init_binary_tree}
/* Initialize the binary tree */
// Initialize the nodes
TreeNode *n1 = newTreeNode(1);
@@ -20,6 +21,7 @@ int main() {
n1->right = n3;
n2->left = n4;
n2->right = n5;
// [endregion]{init_binary_tree}
printf("Initialize the binary tree\n");
printTree(n1);

View File

@@ -49,7 +49,8 @@ int find(ListNode *head, int target) {
/* Driver code */
int main() {
/* Initialize the linked list */
// [region]{init_linked_list}
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the individual nodes
ListNode *n0 = new ListNode(1);
ListNode *n1 = new ListNode(3);
@@ -61,6 +62,7 @@ int main() {
n1->next = n2;
n2->next = n3;
n3->next = n4;
// [endregion]{init_linked_list}
cout << "The initialized linked list is" << endl;
printLinkedList(n0);

View File

@@ -13,58 +13,78 @@ int main() {
cout << "List nums = ";
printVector(nums);
// [region]{access_element}
/* Access an element */
int num = nums[1];
int num = nums[1]; // Access the element at index 1
// [endregion]{access_element}
cout << "Access the element at index 1, giving num = " << num << endl;
// [region]{update_element}
/* Update an element */
nums[1] = 0;
nums[1] = 0; // Update the element at index 1 to 0
// [endregion]{update_element}
cout << "Update the element at index 1 to 0, giving nums = ";
printVector(nums);
// [region]{clear_list}
/* Clear the list */
nums.clear();
// [endregion]{clear_list}
cout << "After clearing the list, nums = ";
printVector(nums);
// [region]{append_element}
/* Append an element at the end */
nums.push_back(1);
nums.push_back(3);
nums.push_back(2);
nums.push_back(5);
nums.push_back(4);
// [endregion]{append_element}
cout << "After adding elements, nums = ";
printVector(nums);
// [region]{insert_element}
/* Insert an element in the middle */
nums.insert(nums.begin() + 3, 6);
nums.insert(nums.begin() + 3, 6); // Insert the number 6 at index 3
// [endregion]{insert_element}
cout << "Insert the number 6 at index 3, giving nums = ";
printVector(nums);
// [region]{remove_element}
/* Remove an element */
nums.erase(nums.begin() + 3);
nums.erase(nums.begin() + 3); // Remove the element at index 3
// [endregion]{remove_element}
cout << "Remove the element at index 3, giving nums = ";
printVector(nums);
// [region]{iterate_list}
/* Traverse the list by index */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums[i];
}
/* Iterate directly over the list elements */
count = 0;
for (int x : nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* Concatenate two lists */
vector<int> nums1 = {6, 8, 7, 10, 9};
// Append list nums1 to nums
nums.insert(nums.end(), nums1.begin(), nums1.end());
// [endregion]{concat_list}
cout << "After appending list nums1 to nums, nums = ";
printVector(nums);
// [region]{sort_list}
/* Sort the list */
sort(nums.begin(), nums.end());
sort(nums.begin(), nums.end()); // After sorting, the list elements are in ascending order
// [endregion]{sort_list}
cout << "After sorting the list, nums = ";
printVector(nums);

View File

@@ -8,33 +8,45 @@
/* Driver code */
int main() {
// [region]{init_stack}
/* Initialize the stack */
stack<int> stack;
// [endregion]{init_stack}
// [region]{push}
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
// [endregion]{push}
cout << "Stack stack = ";
printStack(stack);
// [region]{peek}
/* Access the top element */
int top = stack.top();
// [endregion]{peek}
cout << "Top element top = " << top << endl;
// [region]{pop}
/* Pop an element from the stack */
stack.pop(); // No return value
// [endregion]{pop}
cout << "Popped element pop = " << top << "; after popping, stack = ";
printStack(stack);
// [region]{size}
/* Get the stack size */
int size = stack.size();
// [endregion]{size}
cout << "Stack size = " << size << endl;
// [region]{is_empty}
/* Check whether it is empty */
bool empty = stack.empty();
// [endregion]{is_empty}
cout << "Is the stack empty = " << empty << endl;
return 0;

View File

@@ -8,6 +8,7 @@
/* Driver code */
int main() {
// [region]{init_binary_tree}
/* Initialize the binary tree */
// Initialize the nodes
TreeNode *n1 = new TreeNode(1);
@@ -20,6 +21,7 @@ int main() {
n1->right = n3;
n2->left = n4;
n2->right = n5;
// [endregion]{init_binary_tree}
cout << endl << "Initialize the binary tree\n" << endl;
printTree(n1);

View File

@@ -47,8 +47,9 @@ public class linked_list {
[Test]
public void Test() {
// Initialize the linked list
// Initialize the individual nodes
// [region]{init_linked_list}
// 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);
@@ -59,6 +60,7 @@ public class linked_list {
n1.next = n2;
n2.next = n3;
n3.next = n4;
// [endregion]{init_linked_list}
Console.WriteLine($"Initialized linked list: {n0}");
// Insert a node

View File

@@ -15,52 +15,71 @@ public class list {
List<int> nums = [.. numbers];
Console.WriteLine("List nums = " + string.Join(",", nums));
// [region]{access_element}
/* Access an element */
int num = nums[1];
int num = nums[1]; // Access the element at index 1
// [endregion]{access_element}
Console.WriteLine("Access the element at index 1, giving num = " + num);
// [region]{update_element}
/* Update an element */
nums[1] = 0;
nums[1] = 0; // Update the element at index 1 to 0
// [endregion]{update_element}
Console.WriteLine("Update the element at index 1 to 0, giving nums = " + string.Join(",", nums));
// [region]{clear_list}
/* Clear the list */
nums.Clear();
// [endregion]{clear_list}
Console.WriteLine("After clearing the list, nums = " + string.Join(",", nums));
// [region]{append_element}
/* Append at the end */
nums.Add(1);
nums.Add(3);
nums.Add(2);
nums.Add(5);
nums.Add(4);
// [endregion]{append_element}
Console.WriteLine("After adding elements, nums = " + string.Join(",", nums));
// [region]{insert_element}
/* Insert an element in the middle */
nums.Insert(3, 6);
nums.Insert(3, 6); // Insert the number 6 at index 3
// [endregion]{insert_element}
Console.WriteLine("Insert the number 6 at index 3, giving nums = " + string.Join(",", nums));
// [region]{remove_element}
/* Remove an element */
nums.RemoveAt(3);
nums.RemoveAt(3); // Remove the element at index 3
// [endregion]{remove_element}
Console.WriteLine("Remove the element at index 3, giving nums = " + string.Join(",", nums));
// [region]{iterate_list}
/* Traverse the list by index */
int count = 0;
for (int i = 0; i < nums.Count; i++) {
count += nums[i];
}
/* Iterate directly over the list elements */
count = 0;
foreach (int x in nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* Concatenate two lists */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1);
nums.AddRange(nums1); // Append list nums1 to nums
// [endregion]{concat_list}
Console.WriteLine("After appending list nums1 to nums, nums = " + string.Join(",", nums));
// [region]{sort_list}
/* Sort the list */
nums.Sort(); // After sorting, the list elements are in ascending order
// [endregion]{sort_list}
Console.WriteLine("After sorting the list, nums = " + string.Join(",", nums));
}
}

View File

@@ -9,9 +9,12 @@ namespace hello_algo.chapter_stack_and_queue;
public class stack {
[Test]
public void Test() {
// [region]{init_stack}
/* Initialize the stack */
Stack<int> stack = new();
// [endregion]{init_stack}
// [region]{push}
/* Push elements onto the stack */
stack.Push(1);
stack.Push(3);
@@ -19,22 +22,31 @@ public class stack {
stack.Push(5);
stack.Push(4);
// Note that stack.ToArray() returns elements in reverse insertion order, with the stack top at index 0
// [endregion]{push}
Console.WriteLine("Stack stack = " + string.Join(",", stack));
// [region]{peek}
/* Access the top element */
int peek = stack.Peek();
// [endregion]{peek}
Console.WriteLine("Top element peek = " + peek);
// [region]{pop}
/* Pop an element from the stack */
int pop = stack.Pop();
// [endregion]{pop}
Console.WriteLine("Popped element pop = " + pop + ", after popping, stack = " + string.Join(",", stack));
// [region]{size}
/* Get the stack size */
int size = stack.Count;
// [endregion]{size}
Console.WriteLine("Stack size = " + size);
// [region]{is_empty}
/* Check whether it is empty */
bool isEmpty = stack.Count == 0;
// [endregion]{is_empty}
Console.WriteLine("Is the stack empty = " + isEmpty);
}
}

View File

@@ -9,6 +9,7 @@ namespace hello_algo.chapter_tree;
public class binary_tree {
[Test]
public void Test() {
// [region]{init_binary_tree}
/* Initialize the binary tree */
// Initialize the nodes
TreeNode n1 = new(1);
@@ -21,6 +22,7 @@ public class binary_tree {
n1.right = n3;
n2.left = n4;
n2.right = n5;
// [endregion]{init_binary_tree}
Console.WriteLine("\nInitialize the binary tree\n");
PrintUtil.PrintTree(n1);

View File

@@ -47,7 +47,8 @@ int find(ListNode? head, int target) {
/* Driver code */
void main() {
// Initialize the linked list
// [region]{init_linked_list}
// Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
// Initialize the individual nodes
ListNode n0 = ListNode(1);
ListNode n1 = ListNode(3);
@@ -59,6 +60,7 @@ void main() {
n1.next = n2;
n2.next = n3;
n3.next = n4;
// [endregion]{init_linked_list}
print('The initialized linked list is');
printLinkedList(n0);

View File

@@ -12,51 +12,70 @@ void main() {
List<int> nums = [1, 3, 2, 5, 4];
print('List nums = $nums');
// [region]{access_element}
/* Access an element */
int _num = nums[1];
int _num = nums[1]; // Access the element at index 1
// [endregion]{access_element}
print('Access the element at index 1: _num = $_num');
// [region]{update_element}
/* Update an element */
nums[1] = 0;
nums[1] = 0; // Update the element at index 1 to 0
// [endregion]{update_element}
print('After updating the element at index 1 to 0, nums = $nums');
// [region]{clear_list}
/* Clear the list */
nums.clear();
// [endregion]{clear_list}
print('After clearing the list, nums = $nums');
// [region]{append_element}
/* Append an element at the end */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
// [endregion]{append_element}
print('After adding elements, nums = $nums');
// [region]{insert_element}
/* Insert an element in the middle */
nums.insert(3, 6);
nums.insert(3, 6); // Insert the number 6 at index 3
// [endregion]{insert_element}
print('After inserting 6 at index 3, nums = $nums');
// [region]{remove_element}
/* Remove an element */
nums.removeAt(3);
nums.removeAt(3); // Remove the element at index 3
// [endregion]{remove_element}
print('After removing the element at index 3, nums = $nums');
// [region]{iterate_list}
/* Traverse the list by index */
int count = 0;
for (var i = 0; i < nums.length; i++) {
count += nums[i];
}
/* Iterate directly over the list elements */
count = 0;
for (var x in nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* Concatenate two lists */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.addAll(nums1);
nums.addAll(nums1); // Append list nums1 to nums
// [endregion]{concat_list}
print('After appending list nums1 to nums, nums = $nums');
// [region]{sort_list}
/* Sort the list */
nums.sort();
nums.sort(); // After sorting, the list elements are in ascending order
// [endregion]{sort_list}
print('After sorting the list, nums = $nums');
}

View File

@@ -5,31 +5,43 @@
*/
void main() {
// [region]{init_stack}
/* Initialize the stack */
// Dart has no built-in stack class; a List can be used as a stack
final List<int> stack = [];
// [endregion]{init_stack}
// [region]{push}
/* Push elements onto the stack */
stack.add(1);
stack.add(3);
stack.add(2);
stack.add(5);
stack.add(4);
// [endregion]{push}
print("Stack stack = $stack");
// [region]{peek}
/* Access the top element */
final int peek = stack.last;
// [endregion]{peek}
print("Top element peek = $peek");
// [region]{pop}
/* Pop an element from the stack */
final int pop = stack.removeLast();
// [endregion]{pop}
print("Popped element pop = $pop; after popping, stack = $stack");
// [region]{size}
/* Get the stack size */
final int size = stack.length;
// [endregion]{size}
print("Stack size = $size");
// [region]{is_empty}
/* Check whether it is empty */
final bool isEmpty = stack.isEmpty;
// [endregion]{is_empty}
print("Is the stack empty = $isEmpty");
}

View File

@@ -8,6 +8,7 @@ import '../utils/print_util.dart';
import '../utils/tree_node.dart';
void main() {
// [region]{init_binary_tree}
/* Initialize the binary tree */
// Initialize the nodes
TreeNode n1 = TreeNode(1);
@@ -20,6 +21,7 @@ void main() {
n1.right = n3;
n2.left = n4;
n2.right = n5;
// [endregion]{init_binary_tree}
print("\nInitialize the binary tree\n");
printTree(n1);

View File

@@ -12,6 +12,7 @@ import (
)
func TestLinkedList(t *testing.T) {
// [region]{init_linked_list}
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the individual nodes
n0 := NewListNode(1)
@@ -25,6 +26,7 @@ func TestLinkedList(t *testing.T) {
n1.Next = n2
n2.Next = n3
n3.Next = n4
// [endregion]{init_linked_list}
fmt.Println("The initialized linked list is")
PrintLinkedList(n0)

View File

@@ -16,51 +16,70 @@ func TestList(t *testing.T) {
nums := []int{1, 3, 2, 5, 4}
fmt.Println("List nums =", nums)
// [region]{access_element}
/* Access an element */
num := nums[1] // Access the element at index 1
// [endregion]{access_element}
fmt.Println("Access the element at index 1, giving num =", num)
// [region]{update_element}
/* Update an element */
nums[1] = 0 // Update the element at index 1 to 0
// [endregion]{update_element}
fmt.Println("Update the element at index 1 to 0, giving nums =", nums)
// [region]{clear_list}
/* Clear the list */
nums = nil
// [endregion]{clear_list}
fmt.Println("After clearing the list, nums =", nums)
// [region]{append_element}
/* Append at the end */
nums = append(nums, 1)
nums = append(nums, 3)
nums = append(nums, 2)
nums = append(nums, 5)
nums = append(nums, 4)
// [endregion]{append_element}
fmt.Println("After adding elements, nums =", nums)
// [region]{insert_element}
/* Insert an element in the middle */
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert the number 6 at index 3
// [endregion]{insert_element}
fmt.Println("Insert the number 6 at index 3, giving nums =", nums)
// [region]{remove_element}
/* Remove an element */
nums = append(nums[:3], nums[4:]...) // Remove the element at index 3
// [endregion]{remove_element}
fmt.Println("Remove the element at index 3, giving nums =", nums)
// [region]{iterate_list}
/* Traverse the list by index */
count := 0
for i := 0; i < len(nums); i++ {
count += nums[i]
}
/* Iterate directly over the list elements */
count = 0
for _, x := range nums {
count += x
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* Concatenate two lists */
nums1 := []int{6, 8, 7, 10, 9}
nums = append(nums, nums1...) // Append list nums1 to nums
// [endregion]{concat_list}
fmt.Println("After appending list nums1 to nums, nums =", nums)
// [region]{sort_list}
/* Sort the list */
sort.Ints(nums) // After sorting, the list elements are in ascending order
// [endregion]{sort_list}
fmt.Println("After sorting the list, nums =", nums)
}

View File

@@ -12,35 +12,47 @@ import (
)
func TestStack(t *testing.T) {
// [region]{init_stack}
/* Initialize the stack */
// In Go, a slice is the recommended way to implement a stack
var stack []int
// [endregion]{init_stack}
// [region]{push}
/* Push elements onto the stack */
stack = append(stack, 1)
stack = append(stack, 3)
stack = append(stack, 2)
stack = append(stack, 5)
stack = append(stack, 4)
// [endregion]{push}
fmt.Print("Stack stack = ")
PrintSlice(stack)
// [region]{peek}
/* Access the top element */
peek := stack[len(stack)-1]
// [endregion]{peek}
fmt.Println("Top element peek =", peek)
// [region]{pop}
/* Pop an element from the stack */
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]
// [endregion]{pop}
fmt.Print("Popped element pop = ", pop, ", after popping, stack = ")
PrintSlice(stack)
// [region]{size}
/* Get the stack size */
size := len(stack)
// [endregion]{size}
fmt.Println("Stack size =", size)
// [region]{is_empty}
/* Check whether it is empty */
isEmpty := len(stack) == 0
// [endregion]{is_empty}
fmt.Println("Is the stack empty =", isEmpty)
}

View File

@@ -12,6 +12,7 @@ import (
)
func TestBinaryTree(t *testing.T) {
// [region]{init_binary_tree}
/* Initialize the binary tree */
// Initialize the nodes
n1 := NewTreeNode(1)
@@ -24,6 +25,7 @@ func TestBinaryTree(t *testing.T) {
n1.Right = n3
n2.Left = n4
n2.Right = n5
// [endregion]{init_binary_tree}
fmt.Println("Initialize the binary tree")
PrintTree(n1)

View File

@@ -50,7 +50,8 @@ public class linked_list {
/* Driver code */
public static void main(String[] args) {
/* Initialize the linked list */
// [region]{init_linked_list}
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the individual nodes
ListNode n0 = new ListNode(1);
ListNode n1 = new ListNode(3);
@@ -62,6 +63,7 @@ public class linked_list {
n1.next = n2;
n2.next = n3;
n3.next = n4;
// [endregion]{init_linked_list}
System.out.println("The initialized linked list is");
PrintUtil.printLinkedList(n0);

View File

@@ -16,51 +16,70 @@ public class list {
List<Integer> nums = new ArrayList<>(Arrays.asList(numbers));
System.out.println("List nums = " + nums);
// [region]{access_element}
/* Access an element */
int num = nums.get(1);
int num = nums.get(1); // Access the element at index 1
// [endregion]{access_element}
System.out.println("Access the element at index 1, giving num = " + num);
// [region]{update_element}
/* Update an element */
nums.set(1, 0);
nums.set(1, 0); // Update the element at index 1 to 0
// [endregion]{update_element}
System.out.println("Update the element at index 1 to 0, giving nums = " + nums);
// [region]{clear_list}
/* Clear the list */
nums.clear();
// [endregion]{clear_list}
System.out.println("After clearing the list, nums = " + nums);
// [region]{append_element}
/* Append at the end */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
// [endregion]{append_element}
System.out.println("After adding elements, nums = " + nums);
// [region]{insert_element}
/* Insert an element in the middle */
nums.add(3, 6);
nums.add(3, 6); // Insert the number 6 at index 3
// [endregion]{insert_element}
System.out.println("Insert the number 6 at index 3, giving nums = " + nums);
// [region]{remove_element}
/* Remove an element */
nums.remove(3);
nums.remove(3); // Remove the element at index 3
// [endregion]{remove_element}
System.out.println("Remove the element at index 3, giving nums = " + nums);
// [region]{iterate_list}
/* Traverse the list by index */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums.get(i);
}
/* Iterate directly over the list elements */
for (int x : nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* Concatenate two lists */
List<Integer> nums1 = new ArrayList<>(Arrays.asList(new Integer[] { 6, 8, 7, 10, 9 }));
nums.addAll(nums1);
nums.addAll(nums1); // Append list nums1 to nums
// [endregion]{concat_list}
System.out.println("After appending list nums1 to nums, nums = " + nums);
// [region]{sort_list}
/* Sort the list */
Collections.sort(nums);
Collections.sort(nums); // After sorting, the list elements are in ascending order
// [endregion]{sort_list}
System.out.println("After sorting the list, nums = " + nums);
}
}

View File

@@ -10,31 +10,43 @@ import java.util.*;
public class stack {
public static void main(String[] args) {
// [region]{init_stack}
/* Initialize the stack */
Stack<Integer> stack = new Stack<>();
// [endregion]{init_stack}
// [region]{push}
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
// [endregion]{push}
System.out.println("Stack stack = " + stack);
// [region]{peek}
/* Access the top element */
int peek = stack.peek();
// [endregion]{peek}
System.out.println("Top element peek = " + peek);
// [region]{pop}
/* Pop an element from the stack */
int pop = stack.pop();
// [endregion]{pop}
System.out.println("Popped element pop = " + pop + ", after popping, stack = " + stack);
// [region]{size}
/* Get the stack size */
int size = stack.size();
// [endregion]{size}
System.out.println("Stack size = " + size);
// [region]{is_empty}
/* Check whether it is empty */
boolean isEmpty = stack.isEmpty();
// [endregion]{is_empty}
System.out.println("Is the stack empty = " + isEmpty);
}
}

View File

@@ -10,6 +10,7 @@ import utils.*;
public class binary_tree {
public static void main(String[] args) {
// [region]{init_binary_tree}
/* Initialize the binary tree */
// Initialize the nodes
TreeNode n1 = new TreeNode(1);
@@ -22,6 +23,7 @@ public class binary_tree {
n1.right = n3;
n2.left = n4;
n2.right = n5;
// [endregion]{init_binary_tree}
System.out.println("\nInitialize the binary tree\n");
PrintUtil.printTree(n1);

View File

@@ -48,7 +48,8 @@ function find(head, target) {
}
/* Driver code */
/* Initialize the linked list */
// [region]{init_linked_list}
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the individual nodes
const n0 = new ListNode(1);
const n1 = new ListNode(3);
@@ -60,6 +61,7 @@ n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
// [endregion]{init_linked_list}
console.log('The initialized linked list is');
printLinkedList(n0);

View File

@@ -8,50 +8,69 @@
const nums = [1, 3, 2, 5, 4];
console.log(`List nums = ${nums}`);
// [region]{access_element}
/* Access an element */
const num = nums[1];
const num = nums[1]; // Access the element at index 1
// [endregion]{access_element}
console.log(`Access the element at index 1, giving num = ${num}`);
// [region]{update_element}
/* Update an element */
nums[1] = 0;
nums[1] = 0; // Update the element at index 1 to 0
// [endregion]{update_element}
console.log(`Update the element at index 1 to 0, giving nums = ${nums}`);
// [region]{clear_list}
/* Clear the list */
nums.length = 0;
// [endregion]{clear_list}
console.log(`After clearing the list, nums = ${nums}`);
// [region]{append_element}
/* Append an element at the end */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
// [endregion]{append_element}
console.log(`After appending elements, nums = ${nums}`);
// [region]{insert_element}
/* Insert an element in the middle */
nums.splice(3, 0, 6);
nums.splice(3, 0, 6); // Insert the number 6 at index 3
// [endregion]{insert_element}
console.log(`Insert the number 6 at index 3, giving nums = ${nums}`);
// [region]{remove_element}
/* Remove an element */
nums.splice(3, 1);
nums.splice(3, 1); // Remove the element at index 3
// [endregion]{remove_element}
console.log(`Remove the element at index 3, giving nums = ${nums}`);
// [region]{iterate_list}
/* Traverse the list by index */
let count = 0;
for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* Iterate directly over the list elements */
count = 0;
for (const x of nums) {
count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* Concatenate two lists */
const nums1 = [6, 8, 7, 10, 9];
nums.push(...nums1);
nums.push(...nums1); // Append list nums1 to nums
// [endregion]{concat_list}
console.log(`Append list nums1 to nums, giving nums = ${nums}`);
// [region]{sort_list}
/* Sort the list */
nums.sort((a, b) => a - b);
nums.sort((a, b) => a - b); // After sorting, the list elements are in ascending order
// [endregion]{sort_list}
console.log(`After sorting the list, nums = ${nums}`);

View File

@@ -5,31 +5,43 @@
*/
/* Driver code */
// [region]{init_stack}
/* Initialize the stack */
// JavaScript has no built-in stack class; an Array can be used as a stack
const stack = [];
// [endregion]{init_stack}
// [region]{push}
/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
// [endregion]{push}
console.log('Stack stack =', stack);
// [region]{peek}
/* Access the top element */
const peek = stack[stack.length - 1];
// [endregion]{peek}
console.log('Top element peek =', peek);
// [region]{pop}
/* Pop an element from the stack */
const pop = stack.pop();
// [endregion]{pop}
console.log('Popped element pop =', pop);
console.log('After popping, stack =', stack);
// [region]{size}
/* Get the stack size */
const size = stack.length;
// [endregion]{size}
console.log('Stack size =', size);
// [region]{is_empty}
/* Check whether it is empty */
const isEmpty = stack.length === 0;
// [endregion]{is_empty}
console.log('Is the stack empty =', isEmpty);

View File

@@ -7,6 +7,7 @@
const { TreeNode } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
// [region]{init_binary_tree}
/* Initialize the binary tree */
// Initialize the nodes
let n1 = new TreeNode(1),
@@ -19,6 +20,7 @@ n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
// [endregion]{init_binary_tree}
console.log('\nInitialize the binary tree\n');
printTree(n1);

View File

@@ -52,7 +52,8 @@ fun find(head: ListNode?, target: Int): Int {
/* Driver code */
fun main() {
/* Initialize the linked list */
// [region]{init_linked_list}
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the individual nodes
val n0 = ListNode(1)
val n1 = ListNode(3)
@@ -65,6 +66,7 @@ fun main() {
n1.next = n2
n2.next = n3
n3.next = n4
// [endregion]{init_linked_list}
println("The initialized linked list is")
printLinkedList(n0)

View File

@@ -13,34 +13,47 @@ fun main() {
val nums = mutableListOf(1, 3, 2, 5, 4)
println("List nums = $nums")
// [region]{access_element}
/* Access an element */
val num = nums[1]
val num = nums[1] // Access the element at index 1
// [endregion]{access_element}
println("Accessing the element at index 1 gives num = $num")
// [region]{update_element}
/* Update an element */
nums[1] = 0
nums[1] = 0 // Update the element at index 1 to 0
// [endregion]{update_element}
println("After updating the element at index 1 to 0, nums = $nums")
// [region]{clear_list}
/* Clear the list */
nums.clear()
// [endregion]{clear_list}
println("After clearing the list, nums = $nums")
// [region]{append_element}
/* Append at the end */
nums.add(1)
nums.add(3)
nums.add(2)
nums.add(5)
nums.add(4)
// [endregion]{append_element}
println("After adding elements, nums = $nums")
// [region]{insert_element}
/* Insert an element in the middle */
nums.add(3, 6)
nums.add(3, 6) // Insert the number 6 at index 3
// [endregion]{insert_element}
println("After inserting 6 at index 3, nums = $nums")
// [region]{remove_element}
/* Remove an element */
nums.removeAt(3)
nums.removeAt(3) // Remove the element at index 3
// [endregion]{remove_element}
println("After removing the element at index 3, nums = $nums")
// [region]{iterate_list}
/* Traverse the list by index */
var count = 0
for (i in nums.indices) {
@@ -51,13 +64,18 @@ fun main() {
for (j in nums) {
count += j
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* Concatenate two lists*/
val nums1 = mutableListOf(6, 8, 7, 10, 9)
nums.addAll(nums1)
nums.addAll(nums1) // Append list nums1 to nums
// [endregion]{concat_list}
println("After appending list nums1 to nums, nums = $nums")
// [region]{sort_list}
/* Sort the list */
nums.sort()
nums.sort() // After sorting, the list elements are in ascending order
// [endregion]{sort_list}
println("After sorting the list, nums = $nums")
}

View File

@@ -10,30 +10,42 @@ import java.util.*
/* Driver code */
fun main() {
// [region]{init_stack}
/* Initialize the stack */
val stack = Stack<Int>()
// [endregion]{init_stack}
// [region]{push}
/* Push elements onto the stack */
stack.push(1)
stack.push(3)
stack.push(2)
stack.push(5)
stack.push(4)
// [endregion]{push}
println("Stack stack = $stack")
// [region]{peek}
/* Access the top element */
val peek = stack.peek()
// [endregion]{peek}
println("Top element: peek = $peek")
// [region]{pop}
/* Pop an element from the stack */
val pop = stack.pop()
// [endregion]{pop}
println("Popped element: pop = $pop; stack after removal = $stack")
// [region]{size}
/* Get the stack size */
val size = stack.size
// [endregion]{size}
println("Stack size = $size")
// [region]{is_empty}
/* Check whether it is empty */
val isEmpty = stack.isEmpty()
// [endregion]{is_empty}
println("Is the stack empty? $isEmpty")
}

View File

@@ -11,6 +11,7 @@ import utils.printTree
/* Driver code */
fun main() {
// [region]{init_binary_tree}
/* Initialize the binary tree */
// Initialize the nodes
val n1 = TreeNode(1)
@@ -23,6 +24,7 @@ fun main() {
n1.right = n3
n2.left = n4
n2.right = n5
// [endregion]{init_binary_tree}
println("\nInitialize the binary tree\n")
printTree(n1)

View File

@@ -50,7 +50,8 @@ def find(head: ListNode, target: int) -> int:
"""Driver code"""
if __name__ == "__main__":
# Initialize the linked list
# [region]{init_linked_list}
# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize the individual nodes
n0 = ListNode(1)
n1 = ListNode(3)
@@ -62,6 +63,7 @@ if __name__ == "__main__":
n1.next = n2
n2.next = n3
n3.next = n4
# [endregion]{init_linked_list}
print("The initialized linked list is")
print_linked_list(n0)

View File

@@ -10,47 +10,66 @@ if __name__ == "__main__":
nums: list[int] = [1, 3, 2, 5, 4]
print("\nList nums =", nums)
# [region]{access_element}
# Access an element
x: int = nums[1]
x: int = nums[1] # Access the element at index 1
# [endregion]{access_element}
print("\nAccess the element at index 1, giving x =", x)
# [region]{update_element}
# Update an element
nums[1] = 0
nums[1] = 0 # Update the element at index 1 to 0
# [endregion]{update_element}
print("\nUpdate the element at index 1 to 0, giving nums =", nums)
# [region]{clear_list}
# Clear the list
nums.clear()
# [endregion]{clear_list}
print("\nAfter clearing the list, nums =", nums)
# [region]{append_element}
# Append an element at the end
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
# [endregion]{append_element}
print("\nAfter adding elements, nums =", nums)
# [region]{insert_element}
# Insert an element in the middle
nums.insert(3, 6)
nums.insert(3, 6) # Insert the number 6 at index 3
# [endregion]{insert_element}
print("\nInsert the number 6 at index 3, giving nums =", nums)
# [region]{remove_element}
# Remove an element
nums.pop(3)
nums.pop(3) # Remove the element at index 3
# [endregion]{remove_element}
print("\nRemove the element at index 3, giving nums =", nums)
# [region]{iterate_list}
# Traverse the list by index
count = 0
for i in range(len(nums)):
count += nums[i]
# Iterate directly over the list elements
for num in nums:
count += num
# [endregion]{iterate_list}
# [region]{concat_list}
# Concatenate two lists
nums1 = [6, 8, 7, 10, 9]
nums += nums1
nums += nums1 # Append list nums1 to nums
# [endregion]{concat_list}
print("\nAppend list nums1 to nums, giving nums =", nums)
# [region]{sort_list}
# Sort the list
nums.sort()
nums.sort() # After sorting, the list elements are in ascending order
# [endregion]{sort_list}
print("\nAfter sorting the list, nums =", nums)

View File

@@ -6,31 +6,43 @@ Author: Peng Chen (pengchzn@gmail.com)
"""Driver code"""
if __name__ == "__main__":
# [region]{init_stack}
# Initialize the stack
# Python has no built-in stack class; a list can be used as a stack
stack: list[int] = []
# [endregion]{init_stack}
# [region]{push}
# Push elements onto the stack
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)
# [endregion]{push}
print("Stack stack =", stack)
# [region]{peek}
# Access the top element
peek: int = stack[-1]
# [endregion]{peek}
print("Top element peek =", peek)
# [region]{pop}
# Pop an element from the stack
pop: int = stack.pop()
# [endregion]{pop}
print("Popped element pop =", pop)
print("After popping, stack =", stack)
# [region]{size}
# Get the stack size
size: int = len(stack)
# [endregion]{size}
print("Stack size =", size)
# [region]{is_empty}
# Check whether it is empty
is_empty: bool = len(stack) == 0
# [endregion]{is_empty}
print("Is the stack empty =", is_empty)

View File

@@ -13,6 +13,7 @@ from modules import TreeNode, print_tree
"""Driver code"""
if __name__ == "__main__":
# [region]{init_binary_tree}
# Initialize the binary tree
# Initialize the nodes
n1 = TreeNode(val=1)
@@ -25,6 +26,7 @@ if __name__ == "__main__":
n1.right = n3
n2.left = n4
n2.right = n5
# [endregion]{init_binary_tree}
print("\nInitialize the binary tree\n")
print_tree(n1)

View File

@@ -49,7 +49,8 @@ end
### Driver code ###
if __FILE__ == $0
# Initialize the linked list
# [region]{init_linked_list}
# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize the individual nodes
n0 = ListNode.new(1)
n1 = ListNode.new(3)
@@ -61,6 +62,7 @@ if __FILE__ == $0
n1.next = n2
n2.next = n3
n3.next = n4
# [endregion]{init_linked_list}
puts "The initialized linked list is"
print_linked_list(n0)

View File

@@ -10,34 +10,47 @@ if __FILE__ == $0
nums = [1, 3, 2, 5, 4]
puts "List nums = #{nums}"
# [region]{access_element}
# Access an element
num = nums[1]
num = nums[1] # Access the element at index 1
# [endregion]{access_element}
puts "Access the element at index 1: num = #{num}"
# [region]{update_element}
# Update an element
nums[1] = 0
nums[1] = 0 # Update the element at index 1 to 0
# [endregion]{update_element}
puts "After updating the element at index 1 to 0, nums = #{nums}"
# [region]{clear_list}
# Clear the list
nums.clear
# [endregion]{clear_list}
puts "After clearing the list, nums = #{nums}"
# [region]{append_element}
# Append an element at the end
nums << 1
nums << 3
nums << 2
nums << 5
nums << 4
# [endregion]{append_element}
puts "After adding elements, nums = #{nums}"
# [region]{insert_element}
# Insert an element in the middle
nums.insert(3, 6)
nums.insert(3, 6) # Insert the number 6 at index 3
# [endregion]{insert_element}
puts "After inserting element 6 at index 3, nums = #{nums}"
# [region]{remove_element}
# Remove an element
nums.delete_at(3)
nums.delete_at(3) # Remove the element at index 3
# [endregion]{remove_element}
puts "After removing the element at index 3, nums = #{nums}"
# [region]{iterate_list}
# Traverse the list by index
count = 0
for i in 0...nums.length
@@ -49,12 +62,18 @@ if __FILE__ == $0
nums.each do |x|
count += x
end
# [endregion]{iterate_list}
# [region]{concat_list}
# Concatenate two lists
nums1 = [6, 8, 7, 10, 9]
nums += nums1
# [endregion]{concat_list}
puts "After concatenating nums1 onto nums, nums = #{nums}"
nums = nums.sort { |a, b| a <=> b }
# [region]{sort_list}
# Sort the list
nums = nums.sort { |a, b| a <=> b } # After sorting, the list elements are in ascending order
# [endregion]{sort_list}
puts "After sorting the list, nums = #{nums}"
end

View File

@@ -6,32 +6,44 @@ Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
### Driver code ###
if __FILE__ == $0
# [region]{init_stack}
# Initialize the stack
# Ruby has no built-in stack class; use an Array as a stack
stack = []
# [endregion]{init_stack}
# [region]{push}
# Push elements onto the stack
stack << 1
stack << 3
stack << 2
stack << 5
stack << 4
# [endregion]{push}
puts "Stack stack = #{stack}"
# [region]{peek}
# Access the top element
peek = stack.last
# [endregion]{peek}
puts "Top element peek = #{peek}"
# [region]{pop}
# Pop an element from the stack
pop = stack.pop
# [endregion]{pop}
puts "Popped element pop = #{pop}"
puts "After popping, stack = #{stack}"
# [region]{size}
# Get the stack size
size = stack.length
# [endregion]{size}
puts "Stack size = #{size}"
# [region]{is_empty}
# Check whether it is empty
is_empty = stack.empty?
# [endregion]{is_empty}
puts "Is the stack empty? #{is_empty}"
end

View File

@@ -9,6 +9,7 @@ require_relative '../utils/print_util'
### Driver code ###
if __FILE__ == $0
# [region]{init_binary_tree}
# Initialize the binary tree
# Initialize the nodes
n1 = TreeNode.new(1)
@@ -21,6 +22,7 @@ if __FILE__ == $0
n1.right = n3
n2.left = n4
n2.right = n5
# [endregion]{init_binary_tree}
puts "\nInitialize the binary tree\n\n"
print_tree(n1)

View File

@@ -65,18 +65,21 @@ pub fn find<T: PartialEq>(head: Rc<RefCell<ListNode<T>>>, target: T) -> i32 {
/* Driver code */
fn main() {
/* Initialize the linked list */
// [region]{init_linked_list}
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// 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);
// 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());
n3.borrow_mut().next = Some(n4.clone());
// [endregion]{init_linked_list}
print!("The initialized linked list is ");
print_util::print_linked_list(&n0);

View File

@@ -12,60 +12,79 @@ fn main() {
print!("List nums = ");
print_util::print_array(&nums);
// [region]{access_element}
// Access an element
let num = nums[1];
let num = nums[1]; // Access the element at index 1
// [endregion]{access_element}
println!("\nAccessing the element at index 1 gives num = {num}");
// [region]{update_element}
// Update an element
nums[1] = 0;
nums[1] = 0; // Update the element at index 1 to 0
// [endregion]{update_element}
print!("Update the element at index 1 to 0, giving nums = ");
print_util::print_array(&nums);
// [region]{clear_list}
// Clear the list
nums.clear();
// [endregion]{clear_list}
print!("\nAfter clearing the list, nums = ");
print_util::print_array(&nums);
// [region]{append_element}
// Append an element at the end
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
// [endregion]{append_element}
print!("\nAfter adding elements, nums = ");
print_util::print_array(&nums);
// [region]{insert_element}
// Insert an element in the middle
nums.insert(3, 6);
nums.insert(3, 6); // Insert the number 6 at index 3
// [endregion]{insert_element}
print!("\nInsert the number 6 at index 3, giving nums = ");
print_util::print_array(&nums);
// [region]{remove_element}
// Remove an element
nums.remove(3);
nums.remove(3); // Remove the element at index 3
// [endregion]{remove_element}
print!("\nRemove the element at index 3, giving nums = ");
print_util::print_array(&nums);
// [region]{iterate_list}
// Traverse the list by index
let mut _count = 0;
for i in 0..nums.len() {
_count += nums[i];
}
// Iterate directly over the list elements
_count = 0;
for x in &nums {
_count += x;
}
// [endregion]{iterate_list}
// [region]{concat_list}
// Concatenate two lists
let mut nums1 = vec![6, 8, 7, 10, 9];
nums.append(&mut nums1); // append moves the elements, leaving nums1 empty!
// [endregion]{concat_list}
// nums.extend(&nums1); // extend borrows nums1, leaving its elements available
print!("\nAppend list nums1 to nums, giving nums = ");
print_util::print_array(&nums);
// [region]{sort_list}
// Sort the list
nums.sort();
nums.sort(); // After sorting, the list elements are in ascending order
// [endregion]{sort_list}
print!("\nAfter sorting the list, nums = ");
print_util::print_array(&nums);
}

View File

@@ -8,6 +8,7 @@ use hello_algo_rust::include::{print_util, TreeNode};
/* Driver code */
fn main() {
// [region]{init_binary_tree}
/* Initialize the binary tree */
// Initialize the nodes
let n1 = TreeNode::new(1);
@@ -20,6 +21,7 @@ fn main() {
n1.borrow_mut().right = Some(Rc::clone(&n3));
n2.borrow_mut().left = Some(Rc::clone(&n4));
n2.borrow_mut().right = Some(Rc::clone(&n5));
// [endregion]{init_binary_tree}
println!("\nInitialize the binary tree\n");
print_util::print_tree(&n1);

View File

@@ -144,199 +144,55 @@ end
<!-- [snippet]{init_linked_list} -->
```python title="linked_list.py"
# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize the nodes
n0 = ListNode(1)
n1 = ListNode(3)
n2 = ListNode(2)
n3 = ListNode(5)
n4 = ListNode(4)
# Link the nodes with references
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
[file]{linked_list}-[region]{init_linked_list}
```
```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
n0->next = n1;
n1->next = n2;
n2->next = n3;
n3->next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```java title="linked_list.java"
/* 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
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```csharp title="linked_list.cs"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the 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
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```go title="linked_list.go"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the nodes
n0 := NewListNode(1)
n1 := NewListNode(3)
n2 := NewListNode(2)
n3 := NewListNode(5)
n4 := NewListNode(4)
// Link the nodes with references
n0.Next = n1
n1.Next = n2
n2.Next = n3
n3.Next = n4
[file]{linked_list_test}-[region]{init_linked_list}
```
```swift title="linked_list.swift"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the 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
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
[file]{linked_list}-[region]{init_linked_list}
```
```javascript title="linked_list.js"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the 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
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```typescript title="linked_list.ts"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the 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
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```dart title="linked_list.dart"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the 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
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```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 }));
// Link the nodes with references
n0.borrow_mut().next = Some(n1.clone());
n1.borrow_mut().next = Some(n2.clone());
n2.borrow_mut().next = Some(n3.clone());
n3.borrow_mut().next = Some(n4.clone());
[file]{linked_list}-[region]{init_linked_list}
```
```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
n0->next = n1;
n1->next = n2;
n2->next = n3;
n3->next = n4;
[file]{linked_list}-[region]{init_linked_list}
```
```kotlin title="linked_list.kt"
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the 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;
[file]{linked_list}-[region]{init_linked_list}
```
```ruby title="linked_list.rb"
# Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4
# Initialize the 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
n0.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
[file]{linked_list}-[region]{init_linked_list}
```
<!-- [tutor]{init_linked_list_tutor} -->

View File

@@ -108,82 +108,63 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{access_element} -->
```python title="list.py"
# Access an element
num: int = nums[1] # Access the element at index 1
[file]{list}-[region]{access_element}
# Update an element
nums[1] = 0 # Set the element at index 1 to 0
[file]{list}-[region]{update_element}
```
```cpp title="list.cpp"
/* Access an element */
int num = nums[1]; // Access the element at index 1
[file]{list}-[region]{access_element}
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
[file]{list}-[region]{update_element}
```
```java title="list.java"
/* Access an element */
int num = nums.get(1); // Access the element at index 1
[file]{list}-[region]{access_element}
/* Update an element */
nums.set(1, 0); // Set the element at index 1 to 0
[file]{list}-[region]{update_element}
```
```csharp title="list.cs"
/* Access an element */
int num = nums[1]; // Access the element at index 1
[file]{list}-[region]{access_element}
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
[file]{list}-[region]{update_element}
```
```go title="list_test.go"
/* Access an element */
num := nums[1] // Access the element at index 1
[file]{list_test}-[region]{access_element}
/* Update an element */
nums[1] = 0 // Set the element at index 1 to 0
[file]{list_test}-[region]{update_element}
```
```swift title="list.swift"
/* Access an element */
let num = nums[1] // Access the element at index 1
[file]{list}-[region]{access_element}
/* Update an element */
nums[1] = 0 // Set the element at index 1 to 0
[file]{list}-[region]{update_element}
```
```javascript title="list.js"
/* Access an element */
const num = nums[1]; // Access the element at index 1
[file]{list}-[region]{access_element}
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
[file]{list}-[region]{update_element}
```
```typescript title="list.ts"
/* Access an element */
const num: number = nums[1]; // Access the element at index 1
[file]{list}-[region]{access_element}
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
[file]{list}-[region]{update_element}
```
```dart title="list.dart"
/* Access an element */
int num = nums[1]; // Access the element at index 1
[file]{list}-[region]{access_element}
/* Update an element */
nums[1] = 0; // Set the element at index 1 to 0
[file]{list}-[region]{update_element}
```
```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
[file]{list}-[region]{access_element}
[file]{list}-[region]{update_element}
```
```c title="list.c"
@@ -191,17 +172,15 @@ 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
/* Update an element */
nums[1] = 0 // Set the element at index 1 to 0
[file]{list}-[region]{access_element}
[file]{list}-[region]{update_element}
```
```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
[file]{list}-[region]{access_element}
[file]{list}-[region]{update_element}
```
<!-- [tutor]{access_element_tutor} -->
@@ -209,183 +188,103 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{insert_remove_element} -->
```python title="list.py"
# Clear the list
nums.clear()
[file]{list}-[region]{clear_list}
# Append elements
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
[file]{list}-[region]{append_element}
# Insert an element in the middle
nums.insert(3, 6) # Insert 6 at index 3
[file]{list}-[region]{insert_element}
# Remove an element
nums.pop(3) # Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```cpp title="list.cpp"
/* Clear the list */
nums.clear();
[file]{list}-[region]{clear_list}
/* Append elements */
nums.push_back(1);
nums.push_back(3);
nums.push_back(2);
nums.push_back(5);
nums.push_back(4);
[file]{list}-[region]{append_element}
/* Insert an element in the middle */
nums.insert(nums.begin() + 3, 6); // Insert 6 at index 3
[file]{list}-[region]{insert_element}
/* Remove an element */
nums.erase(nums.begin() + 3); // Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```java title="list.java"
/* Clear the list */
nums.clear();
[file]{list}-[region]{clear_list}
/* Append elements */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
[file]{list}-[region]{append_element}
/* Insert an element in the middle */
nums.add(3, 6); // Insert 6 at index 3
[file]{list}-[region]{insert_element}
/* Remove an element */
nums.remove(3); // Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```csharp title="list.cs"
/* Clear the list */
nums.Clear();
[file]{list}-[region]{clear_list}
/* Append elements */
nums.Add(1);
nums.Add(3);
nums.Add(2);
nums.Add(5);
nums.Add(4);
[file]{list}-[region]{append_element}
/* Insert an element in the middle */
nums.Insert(3, 6); // Insert 6 at index 3
[file]{list}-[region]{insert_element}
/* Remove an element */
nums.RemoveAt(3); // Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```go title="list_test.go"
/* Clear the list */
nums = nil
[file]{list_test}-[region]{clear_list}
/* Append elements */
nums = append(nums, 1)
nums = append(nums, 3)
nums = append(nums, 2)
nums = append(nums, 5)
nums = append(nums, 4)
[file]{list_test}-[region]{append_element}
/* Insert an element in the middle */
nums = append(nums[:3], append([]int{6}, nums[3:]...)...) // Insert 6 at index 3
[file]{list_test}-[region]{insert_element}
/* Remove an element */
nums = append(nums[:3], nums[4:]...) // Remove the element at index 3
[file]{list_test}-[region]{remove_element}
```
```swift title="list.swift"
/* Clear the list */
nums.removeAll()
[file]{list}-[region]{clear_list}
/* Append elements */
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
[file]{list}-[region]{append_element}
/* Insert an element in the middle */
nums.insert(6, at: 3) // Insert 6 at index 3
[file]{list}-[region]{insert_element}
/* Remove an element */
nums.remove(at: 3) // Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```javascript title="list.js"
/* Clear the list */
nums.length = 0;
[file]{list}-[region]{clear_list}
/* Append elements */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
[file]{list}-[region]{append_element}
/* Insert an element in the middle */
nums.splice(3, 0, 6); // Insert 6 at index 3
[file]{list}-[region]{insert_element}
/* Remove an element */
nums.splice(3, 1); // Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```typescript title="list.ts"
/* Clear the list */
nums.length = 0;
[file]{list}-[region]{clear_list}
/* Append elements */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
[file]{list}-[region]{append_element}
/* Insert an element in the middle */
nums.splice(3, 0, 6); // Insert 6 at index 3
[file]{list}-[region]{insert_element}
/* Remove an element */
nums.splice(3, 1); // Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```dart title="list.dart"
/* Clear the list */
nums.clear();
[file]{list}-[region]{clear_list}
/* Append elements */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
[file]{list}-[region]{append_element}
/* Insert an element in the middle */
nums.insert(3, 6); // Insert 6 at index 3
[file]{list}-[region]{insert_element}
/* Remove an element */
nums.removeAt(3); // Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```rust title="list.rs"
/* Clear the list */
nums.clear();
[file]{list}-[region]{clear_list}
/* Append elements */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
[file]{list}-[region]{append_element}
/* Insert an element in the middle */
nums.insert(3, 6); // Insert 6 at index 3
[file]{list}-[region]{insert_element}
/* Remove an element */
nums.remove(3); // Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```c title="list.c"
@@ -393,39 +292,23 @@ nums.remove(3); // Remove the element at index 3
```
```kotlin title="list.kt"
/* Clear the list */
nums.clear();
[file]{list}-[region]{clear_list}
/* Append elements */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
[file]{list}-[region]{append_element}
/* Insert an element in the middle */
nums.add(3, 6); // Insert 6 at index 3
[file]{list}-[region]{insert_element}
/* Remove an element */
nums.removeAt(3); // Remove the element at index 3
[file]{list}-[region]{remove_element}
```
```ruby title="list.rb"
# Clear the list
nums.clear
[file]{list}-[region]{clear_list}
# Append elements
nums << 1
nums << 3
nums << 2
nums << 5
nums << 4
[file]{list}-[region]{append_element}
# Insert an element in the middle
nums.insert(3, 6) # Insert 6 at index 3
[file]{list}-[region]{insert_element}
# Remove an element
nums.delete_at(3) # Remove the element at index 3
[file]{list}-[region]{remove_element}
```
<!-- [tutor]{insert_remove_element_tutor} -->
@@ -433,139 +316,43 @@ https://pythontutor.com/render.html#code=%22%22%22Driver%20Code%22%22%22%0Aif%20
<!-- [snippet]{iterate_list} -->
```python title="list.py"
# Traverse the list by index
count = 0
for i in range(len(nums)):
count += nums[i]
# Traverse list elements directly
for num in nums:
count += num
[file]{list}-[region]{iterate_list}
```
```cpp title="list.cpp"
/* Traverse the list by index */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums[i];
}
/* Traverse list elements directly */
count = 0;
for (int num : nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```java title="list.java"
/* Traverse the list by index */
int count = 0;
for (int i = 0; i < nums.size(); i++) {
count += nums.get(i);
}
/* Traverse list elements directly */
for (int num : nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```csharp title="list.cs"
/* Traverse the list by index */
int count = 0;
for (int i = 0; i < nums.Count; i++) {
count += nums[i];
}
/* Traverse list elements directly */
count = 0;
foreach (int num in nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```go title="list_test.go"
/* Traverse the list by index */
count := 0
for i := 0; i < len(nums); i++ {
count += nums[i]
}
/* Traverse list elements directly */
count = 0
for _, num := range nums {
count += num
}
[file]{list_test}-[region]{iterate_list}
```
```swift title="list.swift"
/* Traverse the list by index */
var count = 0
for i in nums.indices {
count += nums[i]
}
/* Traverse list elements directly */
count = 0
for num in nums {
count += num
}
[file]{list}-[region]{iterate_list}
```
```javascript title="list.js"
/* Traverse the list by index */
let count = 0;
for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* Traverse list elements directly */
count = 0;
for (const num of nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```typescript title="list.ts"
/* Traverse the list by index */
let count = 0;
for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* Traverse list elements directly */
count = 0;
for (const num of nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```dart title="list.dart"
/* Traverse the list by index */
int count = 0;
for (var i = 0; i < nums.length; i++) {
count += nums[i];
}
/* Traverse list elements directly */
count = 0;
for (var num in nums) {
count += num;
}
[file]{list}-[region]{iterate_list}
```
```rust title="list.rs"
// Traverse the list by index
let mut _count = 0;
for i in 0..nums.len() {
_count += nums[i];
}
// Traverse list elements directly
_count = 0;
for num in &nums {
_count += num;
}
[file]{list}-[region]{iterate_list}
```
```c title="list.c"
@@ -573,30 +360,11 @@ for num in &nums {
```
```kotlin title="list.kt"
/* Traverse the list by index */
var count = 0
for (i in nums.indices) {
count += nums[i]
}
/* Traverse list elements directly */
for (num in nums) {
count += num
}
[file]{list}-[region]{iterate_list}
```
```ruby title="list.rb"
# Traverse the list by index
count = 0
for i in 0...nums.length
count += nums[i]
end
# Traverse list elements directly
count = 0
for num in nums
count += num
end
[file]{list}-[region]{iterate_list}
```
<!-- [tutor]{iterate_list_tutor} -->
@@ -604,64 +372,43 @@ 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
[file]{list}-[region]{concat_list}
```
```cpp title="list.cpp"
/* Concatenate two lists */
vector<int> nums1 = { 6, 8, 7, 10, 9 };
// Append nums1 to nums
nums.insert(nums.end(), nums1.begin(), nums1.end());
[file]{list}-[region]{concat_list}
```
```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
[file]{list}-[region]{concat_list}
```
```csharp title="list.cs"
/* Concatenate two lists */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1); // Append nums1 to nums
[file]{list}-[region]{concat_list}
```
```go title="list_test.go"
/* Concatenate two lists */
nums1 := []int{6, 8, 7, 10, 9}
nums = append(nums, nums1...) // Append nums1 to nums
[file]{list_test}-[region]{concat_list}
```
```swift title="list.swift"
/* Concatenate two lists */
let nums1 = [6, 8, 7, 10, 9]
nums.append(contentsOf: nums1) // Append nums1 to nums
[file]{list}-[region]{concat_list}
```
```javascript title="list.js"
/* Concatenate two lists */
const nums1 = [6, 8, 7, 10, 9];
nums.push(...nums1); // Append nums1 to nums
[file]{list}-[region]{concat_list}
```
```typescript title="list.ts"
/* Concatenate two lists */
const nums1: number[] = [6, 8, 7, 10, 9];
nums.push(...nums1); // Append nums1 to nums
[file]{list}-[region]{concat_list}
```
```dart title="list.dart"
/* Concatenate two lists */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.addAll(nums1); // Append nums1 to nums
[file]{list}-[region]{concat_list}
```
```rust title="list.rs"
/* Concatenate two lists */
let nums1: Vec<i32> = vec![6, 8, 7, 10, 9];
nums.extend(nums1);
[file]{list}-[region]{concat_list}
```
```c title="list.c"
@@ -669,15 +416,11 @@ 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
[file]{list}-[region]{concat_list}
```
```ruby title="list.rb"
# Concatenate two lists
nums1 = [6, 8, 7, 10, 9]
nums += nums1
[file]{list}-[region]{concat_list}
```
<!-- [tutor]{concat_list_tutor} -->
@@ -685,53 +428,43 @@ 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
[file]{list}-[region]{sort_list}
```
```cpp title="list.cpp"
/* Sort the list */
sort(nums.begin(), nums.end()); // After sorting, elements are in ascending order
[file]{list}-[region]{sort_list}
```
```java title="list.java"
/* Sort the list */
Collections.sort(nums); // After sorting, elements are in ascending order
[file]{list}-[region]{sort_list}
```
```csharp title="list.cs"
/* Sort the list */
nums.Sort(); // After sorting, elements are in ascending order
[file]{list}-[region]{sort_list}
```
```go title="list_test.go"
/* Sort the list */
sort.Ints(nums) // After sorting, elements are in ascending order
[file]{list_test}-[region]{sort_list}
```
```swift title="list.swift"
/* Sort the list */
nums.sort() // After sorting, elements are in ascending order
[file]{list}-[region]{sort_list}
```
```javascript title="list.js"
/* Sort the list */
nums.sort((a, b) => a - b); // After sorting, elements are in ascending order
[file]{list}-[region]{sort_list}
```
```typescript title="list.ts"
/* Sort the list */
nums.sort((a, b) => a - b); // After sorting, elements are in ascending order
[file]{list}-[region]{sort_list}
```
```dart title="list.dart"
/* Sort the list */
nums.sort(); // After sorting, elements are in ascending order
[file]{list}-[region]{sort_list}
```
```rust title="list.rs"
/* Sort the list */
nums.sort(); // After sorting, elements are in ascending order
[file]{list}-[region]{sort_list}
```
```c title="list.c"
@@ -739,13 +472,11 @@ 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
[file]{list}-[region]{sort_list}
```
```ruby title="list.rb"
# Sort the list
nums = nums.sort { |a, b| a <=> b } # After sorting, elements are in ascending order
[file]{list}-[region]{sort_list}
```
<!-- [tutor]{sort_list_tutor} -->

View File

@@ -1,225 +1,128 @@
<!-- [snippet]{stack_operations} -->
```python title="stack.py"
# Initialize a stack
# Python has no built-in stack class; use a list as a stack
stack: list[int] = []
[file]{stack}-[region]{init_stack}
# Push elements
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)
[file]{stack}-[region]{push}
# Access the top element
peek: int = stack[-1]
[file]{stack}-[region]{peek}
# Pop an element
pop: int = stack.pop()
[file]{stack}-[region]{pop}
# Get the stack size
size: int = len(stack)
[file]{stack}-[region]{size}
# Check whether the stack is empty
is_empty: bool = len(stack) == 0
[file]{stack}-[region]{is_empty}
```
```cpp title="stack.cpp"
/* Initialize a stack */
stack<int> stack;
[file]{stack}-[region]{init_stack}
/* Push elements */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
[file]{stack}-[region]{push}
/* Access the top element */
int top = stack.top();
[file]{stack}-[region]{peek}
/* Pop an element */
stack.pop(); // No return value
[file]{stack}-[region]{pop}
/* Get the stack size */
int size = stack.size();
[file]{stack}-[region]{size}
/* Check whether the stack is empty */
bool empty = stack.empty();
[file]{stack}-[region]{is_empty}
```
```java title="stack.java"
/* Initialize a stack */
Stack<Integer> stack = new Stack<>();
[file]{stack}-[region]{init_stack}
/* Push elements */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
[file]{stack}-[region]{push}
/* Access the top element */
int peek = stack.peek();
[file]{stack}-[region]{peek}
/* Pop an element */
int pop = stack.pop();
[file]{stack}-[region]{pop}
/* Get the stack size */
int size = stack.size();
[file]{stack}-[region]{size}
/* Check whether the stack is empty */
boolean isEmpty = stack.isEmpty();
[file]{stack}-[region]{is_empty}
```
```csharp title="stack.cs"
/* Initialize a stack */
Stack<int> stack = new();
[file]{stack}-[region]{init_stack}
/* Push elements */
stack.Push(1);
stack.Push(3);
stack.Push(2);
stack.Push(5);
stack.Push(4);
[file]{stack}-[region]{push}
/* Access the top element */
int peek = stack.Peek();
[file]{stack}-[region]{peek}
/* Pop an element */
int pop = stack.Pop();
[file]{stack}-[region]{pop}
/* Get the stack size */
int size = stack.Count;
[file]{stack}-[region]{size}
/* Check whether the stack is empty */
bool isEmpty = stack.Count == 0;
[file]{stack}-[region]{is_empty}
```
```go title="stack_test.go"
/* Initialize a stack */
// In Go, a slice is recommended for use as a stack
var stack []int
[file]{stack_test}-[region]{init_stack}
/* Push elements */
stack = append(stack, 1)
stack = append(stack, 3)
stack = append(stack, 2)
stack = append(stack, 5)
stack = append(stack, 4)
[file]{stack_test}-[region]{push}
/* Access the top element */
peek := stack[len(stack)-1]
[file]{stack_test}-[region]{peek}
/* Pop an element */
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]
[file]{stack_test}-[region]{pop}
/* Get the stack size */
size := len(stack)
[file]{stack_test}-[region]{size}
/* Check whether the stack is empty */
isEmpty := len(stack) == 0
[file]{stack_test}-[region]{is_empty}
```
```swift title="stack.swift"
/* Initialize a stack */
// Swift has no built-in stack class; use an Array as a stack
var stack: [Int] = []
[file]{stack}-[region]{init_stack}
/* Push elements */
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)
[file]{stack}-[region]{push}
/* Access the top element */
let peek = stack.last!
[file]{stack}-[region]{peek}
/* Pop an element */
let pop = stack.removeLast()
[file]{stack}-[region]{pop}
/* Get the stack size */
let size = stack.count
[file]{stack}-[region]{size}
/* Check whether the stack is empty */
let isEmpty = stack.isEmpty
[file]{stack}-[region]{is_empty}
```
```javascript title="stack.js"
/* Initialize a stack */
// JavaScript has no built-in stack class; use an Array as a stack
const stack = [];
[file]{stack}-[region]{init_stack}
/* Push elements */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
[file]{stack}-[region]{push}
/* Access the top element */
const peek = stack[stack.length-1];
[file]{stack}-[region]{peek}
/* Pop an element */
const pop = stack.pop();
[file]{stack}-[region]{pop}
/* Get the stack size */
const size = stack.length;
[file]{stack}-[region]{size}
/* Check whether the stack is empty */
const is_empty = stack.length === 0;
[file]{stack}-[region]{is_empty}
```
```typescript title="stack.ts"
/* Initialize a stack */
// TypeScript has no built-in stack class; use an Array as a stack
const stack: number[] = [];
[file]{stack}-[region]{init_stack}
/* Push elements */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
[file]{stack}-[region]{push}
/* Access the top element */
const peek = stack[stack.length - 1];
[file]{stack}-[region]{peek}
/* Pop an element */
const pop = stack.pop();
[file]{stack}-[region]{pop}
/* Get the stack size */
const size = stack.length;
[file]{stack}-[region]{size}
/* Check whether the stack is empty */
const is_empty = stack.length === 0;
[file]{stack}-[region]{is_empty}
```
```dart title="stack.dart"
/* Initialize a stack */
// Dart has no built-in stack class; use a List as a stack
List<int> stack = [];
[file]{stack}-[region]{init_stack}
/* Push elements */
stack.add(1);
stack.add(3);
stack.add(2);
stack.add(5);
stack.add(4);
[file]{stack}-[region]{push}
/* Access the top element */
int peek = stack.last;
[file]{stack}-[region]{peek}
/* Pop an element */
int pop = stack.removeLast();
[file]{stack}-[region]{pop}
/* Get the stack size */
int size = stack.length;
[file]{stack}-[region]{size}
/* Check whether the stack is empty */
bool isEmpty = stack.isEmpty;
[file]{stack}-[region]{is_empty}
```
```rust title="stack.rs"
@@ -252,52 +155,31 @@ let is_empty = stack.is_empty();
```
```kotlin title="stack.kt"
/* Initialize a stack */
val stack = Stack<Int>()
[file]{stack}-[region]{init_stack}
/* Push elements */
stack.push(1)
stack.push(3)
stack.push(2)
stack.push(5)
stack.push(4)
[file]{stack}-[region]{push}
/* Access the top element */
val peek = stack.peek()
[file]{stack}-[region]{peek}
/* Pop an element */
val pop = stack.pop()
[file]{stack}-[region]{pop}
/* Get the stack size */
val size = stack.size
[file]{stack}-[region]{size}
/* Check whether the stack is empty */
val isEmpty = stack.isEmpty()
[file]{stack}-[region]{is_empty}
```
```ruby title="stack.rb"
# Initialize a stack
# Ruby has no built-in stack class; use an Array as a stack
stack = []
[file]{stack}-[region]{init_stack}
# Push elements
stack << 1
stack << 3
stack << 2
stack << 5
stack << 4
[file]{stack}-[region]{push}
# Access the top element
peek = stack.last
[file]{stack}-[region]{peek}
# Pop an element
pop = stack.pop
[file]{stack}-[region]{pop}
# Get the stack size
size = stack.length
[file]{stack}-[region]{size}
# Check whether the stack is empty
is_empty = stack.empty?
[file]{stack}-[region]{is_empty}
```
<!-- [tutor]{stack_operations_tutor} -->

View File

@@ -174,194 +174,55 @@ end
<!-- [snippet]{init_binary_tree} -->
```python title="binary_tree.py"
# Initialize a binary tree
# Initialize 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)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
[file]{binary_tree}-[region]{init_binary_tree}
```
```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)
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```java title="binary_tree.java"
// 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)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```csharp title="binary_tree.cs"
/* Initialize a binary tree */
// Initialize 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)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```go title="binary_tree.go"
/* Initialize a binary tree */
// Initialize nodes
n1 := NewTreeNode(1)
n2 := NewTreeNode(2)
n3 := NewTreeNode(3)
n4 := NewTreeNode(4)
n5 := NewTreeNode(5)
// Connect nodes with references (pointers)
n1.Left = n2
n1.Right = n3
n2.Left = n4
n2.Right = n5
[file]{binary_tree_test}-[region]{init_binary_tree}
```
```swift title="binary_tree.swift"
// Initialize 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)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
[file]{binary_tree}-[region]{init_binary_tree}
```
```javascript title="binary_tree.js"
/* Initialize a binary tree */
// Initialize 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)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```typescript title="binary_tree.ts"
/* Initialize a binary tree */
// Initialize 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)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```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)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```rust title="binary_tree.rs"
// Initialize 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);
[file]{binary_tree}-[region]{init_binary_tree}
```
```c title="binary_tree.c"
/* Initialize a binary tree */
// Initialize 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)
n1->left = n2;
n1->right = n3;
n2->left = n4;
n2->right = n5;
[file]{binary_tree}-[region]{init_binary_tree}
```
```kotlin title="binary_tree.kt"
// Initialize 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)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
[file]{binary_tree}-[region]{init_binary_tree}
```
```ruby title="binary_tree.rb"
# Initialize a binary tree
# Initialize 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)
n1.left = n2
n1.right = n3
n2.left = n4
n2.right = n5
[file]{binary_tree}-[region]{init_binary_tree}
```
<!-- [tutor]{init_binary_tree_tutor} -->

View File

@@ -54,7 +54,8 @@ func find(head: ListNode, target: Int) -> Int {
enum LinkedList {
/* Driver code */
static func main() {
/* Initialize the linked list */
// [region]{init_linked_list}
/* Initialize the linked list 1 -> 3 -> 2 -> 5 -> 4 */
// Initialize the individual nodes
let n0 = ListNode(x: 1)
let n1 = ListNode(x: 3)
@@ -66,6 +67,7 @@ enum LinkedList {
n1.next = n2
n2.next = n3
n3.next = n4
// [endregion]{init_linked_list}
print("The initialized linked list is")
PrintUtil.printLinkedList(head: n0)

View File

@@ -12,52 +12,71 @@ enum List {
var nums = [1, 3, 2, 5, 4]
print("List nums = \(nums)")
// [region]{access_element}
/* Access an element */
let num = nums[1]
let num = nums[1] // Access the element at index 1
// [endregion]{access_element}
print("Access the element at index 1; num = \(num)")
// [region]{update_element}
/* Update an element */
nums[1] = 0
nums[1] = 0 // Update the element at index 1 to 0
// [endregion]{update_element}
print("After updating the element at index 1 to 0, nums = \(nums)")
// [region]{clear_list}
/* Clear the list */
nums.removeAll()
// [endregion]{clear_list}
print("After clearing the list, nums = \(nums)")
// [region]{append_element}
/* Append at the end */
nums.append(1)
nums.append(3)
nums.append(2)
nums.append(5)
nums.append(4)
// [endregion]{append_element}
print("After appending elements, nums = \(nums)")
// [region]{insert_element}
/* Insert an element in the middle */
nums.insert(6, at: 3)
nums.insert(6, at: 3) // Insert the number 6 at index 3
// [endregion]{insert_element}
print("After inserting 6 at index 3, nums = \(nums)")
// [region]{remove_element}
/* Remove an element */
nums.remove(at: 3)
nums.remove(at: 3) // Remove the element at index 3
// [endregion]{remove_element}
print("After removing the element at index 3, nums = \(nums)")
// [region]{iterate_list}
/* Traverse the list by index */
var count = 0
for i in nums.indices {
count += nums[i]
}
/* Iterate directly over the list elements */
count = 0
for x in nums {
count += x
}
// [endregion]{iterate_list}
// [region]{concat_list}
/* Concatenate two lists */
let nums1 = [6, 8, 7, 10, 9]
nums.append(contentsOf: nums1)
nums.append(contentsOf: nums1) // Append list nums1 to nums
// [endregion]{concat_list}
print("After appending list nums1 to nums, nums = \(nums)")
// [region]{sort_list}
/* Sort the list */
nums.sort()
nums.sort() // After sorting, the list elements are in ascending order
// [endregion]{sort_list}
print("After sorting the list, nums = \(nums)")
}
}

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