Add destructors to the C++ codes.

This commit is contained in:
Yudong Jin
2023-01-14 19:52:11 +08:00
parent 87acfc91ab
commit bb657f9517
19 changed files with 121 additions and 24 deletions

View File

@@ -245,6 +245,8 @@ elementAddr = firtstElementAddr + elementLength * elementIndex
for (int i = 0; i < size; i++) {
res[i] = nums[i];
}
// 释放内存
delete[] nums;
// 返回扩展后的新数组
return res;
}

View File

@@ -748,6 +748,11 @@ comments: true
nums = new int[numsCapacity];
}
/* 析构函数 */
~MyList() {
delete[] nums;
}
/* 获取列表长度(即当前元素数量)*/
int size() {
return numsSize;
@@ -818,14 +823,14 @@ comments: true
void extendCapacity() {
// 新建一个长度为 size * extendRatio 的数组,并将原数组拷贝到新数组
int newCapacity = capacity() * extendRatio;
int* extend = new int[newCapacity];
int* tmp = nums;
nums = new int[newCapacity];
// 将原数组中的所有元素复制到新数组
for (int i = 0; i < size(); i++) {
extend[i] = nums[i];
nums[i] = tmp[i];
}
int* temp = nums;
nums = extend;
delete[] temp;
// 释放内存
delete[] tmp;
numsCapacity = newCapacity;
}
};

View File

@@ -507,7 +507,7 @@ $$
const int a = 0;
int b = 0;
vector<int> nums(10000);
ListNode* node = new ListNode(0);
ListNode node(0);
// 循环中的变量占用 O(1) 空间
for (int i = 0; i < n; i++) {
int c = 0;
@@ -654,9 +654,9 @@ $$
// 长度为 n 的数组占用 O(n) 空间
vector<int> nums(n);
// 长度为 n 的列表占用 O(n) 空间
vector<ListNode*> nodes;
vector<ListNode> nodes;
for (int i = 0; i < n; i++) {
nodes.push_back(new ListNode(i));
nodes.push_back(ListNode(i));
}
// 长度为 n 的哈希表占用 O(n) 空间
unordered_map<int, string> map;

View File

@@ -330,6 +330,10 @@ comments: true
rear = nullptr;
queSize = 0;
}
~LinkedListQueue() {
delete front;
delete rear;
}
/* 获取队列的长度 */
int size() {
return queSize;
@@ -784,6 +788,9 @@ comments: true
cap = capacity;
nums = new int[capacity];
}
~ArrayQueue() {
delete[] nums;
}
/* 获取队列的容量 */
int capacity() {
return cap;

View File

@@ -324,6 +324,9 @@ comments: true
stackTop = nullptr;
stkSize = 0;
}
~LinkedListStack() {
freeMemoryLinkedList(stackTop);
}
/* 获取栈的长度 */
int size() {
return stkSize;

View File

@@ -22,19 +22,15 @@ comments: true
-`cur.val = num` ,说明找到目标结点,跳出循环并返回该结点即可;
=== "Step 1"
![bst_search_1](binary_search_tree.assets/bst_search_1.png)
=== "Step 2"
![bst_search_2](binary_search_tree.assets/bst_search_2.png)
=== "Step 3"
![bst_search_3](binary_search_tree.assets/bst_search_3.png)
=== "Step 4"
![bst_search_4](binary_search_tree.assets/bst_search_4.png)
二叉搜索树的查找操作和二分查找算法如出一辙,也是在每轮排除一半情况。循环次数最多为二叉树的高度,当二叉树平衡时,使用 $O(\log n)$ 时间。