mirror of
https://github.com/krahets/hello-algo.git
synced 2025-12-19 07:17:54 +08:00
Free memory after removing
a node from a LinkedList or TreeNode.
This commit is contained in:
@@ -21,6 +21,8 @@ void remove(ListNode* n0) {
|
||||
ListNode* P = n0->next;
|
||||
ListNode* n1 = P->next;
|
||||
n0->next = n1;
|
||||
// 释放内存
|
||||
delete P;
|
||||
}
|
||||
|
||||
/* 访问链表中索引为 index 的结点 */
|
||||
|
||||
@@ -50,7 +50,10 @@ public:
|
||||
int poll() {
|
||||
int num = peek();
|
||||
// 删除头结点
|
||||
ListNode *tmp = front;
|
||||
front = front->next;
|
||||
// 释放内存
|
||||
delete tmp;
|
||||
queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
@@ -39,7 +39,10 @@ public:
|
||||
/* 出栈 */
|
||||
int pop() {
|
||||
int num = top();
|
||||
ListNode *tmp = stackTop;
|
||||
stackTop = stackTop->next;
|
||||
// 释放内存
|
||||
delete tmp;
|
||||
stkSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
@@ -96,11 +96,13 @@ public:
|
||||
// 删除结点 cur
|
||||
if (pre->left == cur) pre->left = child;
|
||||
else pre->right = child;
|
||||
// 释放内存
|
||||
delete cur;
|
||||
}
|
||||
// 子结点数量 = 2
|
||||
else {
|
||||
// 获取中序遍历中 cur 的下一个结点
|
||||
TreeNode* nex = min(cur->right);
|
||||
TreeNode* nex = getInOrderNext(cur->right);
|
||||
int tmp = nex->val;
|
||||
// 递归删除结点 nex
|
||||
remove(nex->val);
|
||||
@@ -110,8 +112,8 @@ public:
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* 获取最小结点 */
|
||||
TreeNode* min(TreeNode* root) {
|
||||
/* 获取中序遍历中的下一个结点(仅适用于 root 有左子结点的情况) */
|
||||
TreeNode* getInOrderNext(TreeNode* root) {
|
||||
if (root == nullptr) return root;
|
||||
// 循环访问左子结点,直到叶结点时为最小结点,跳出
|
||||
while (root->left != nullptr) {
|
||||
|
||||
@@ -33,6 +33,7 @@ int main() {
|
||||
PrintUtil::printTree(n1);
|
||||
// 删除结点 P
|
||||
n1->left = n2;
|
||||
delete P; // 释放内存
|
||||
cout << endl << "删除结点 P 后\n" << endl;
|
||||
PrintUtil::printTree(n1);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user