Skip to content

feat: cpp memory improve #160

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions cpp/models/ListNode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,42 @@

#include "ListNode.h"

ListNode *IntArrayToListNode(std::vector<int> &arr) {
auto dummy = new ListNode(), p = dummy;
ListNode *IntArrayToListNode(const std::vector<int> &arr) {
ListNode dummy = ListNode();
ListNode *p = &dummy;
for (auto val : arr) {
p->next = new ListNode(val);
p = p->next;
}
return dummy->next;
p = dummy.next;
dummy.next = nullptr; // Prevent memory leak
return p;
}

std::vector<int> &ListNodeToIntArray(ListNode *head) {
auto *arr = new std::vector<int>();
std::vector<int> ListNodeToIntArray(ListNode *head) {
auto arr = std::vector<int>();
while (head != nullptr) {
arr->push_back(head->val);
arr.push_back(head->val);
head = head->next;
}
return *arr;
return arr;
}

ListNode *IntArrayToListNodeCycle(std::vector<int> &arr, int pos) {
auto dummy = new ListNode(), p = dummy;
ListNode dummy = ListNode();
ListNode *p = &dummy;
ListNode *cycle = nullptr;
for (int i = 0; i < static_cast<int>(arr.size()); i++) {
for (size_t i = 0; i < arr.size(); ++i) {
p->next = new ListNode(arr[i]);
p = p->next;
if (i == pos) {
cycle = p;
}
}
p->next = cycle;
return dummy->next;
p = dummy.next;
dummy.next = nullptr; // Prevent memory leak
return p;
}

std::tuple<ListNode *, ListNode *>
Expand Down
4 changes: 2 additions & 2 deletions cpp/models/ListNode.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ struct ListNode {
}
};

ListNode *IntArrayToListNode(std::vector<int> &arr);
ListNode *IntArrayToListNode(const std::vector<int> &arr);

std::vector<int> &ListNodeToIntArray(ListNode *head);
std::vector<int> ListNodeToIntArray(ListNode *head);

ListNode *IntArrayToListNodeCycle(std::vector<int> &arr, int pos);

Expand Down
24 changes: 22 additions & 2 deletions cpp/models/NodeNeighbors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@

#include "NodeNeighbors.h"
#include <unordered_set>
#include <queue>

Node *JsonArrayToNodeNeighbors(vector<vector<int>> arr) {
Node *JsonArrayToNodeNeighbors(const vector<vector<int>>& arr) {
if (arr.empty()) {
return nullptr;
}
vector<Node *> nodes = vector<Node *>(arr.size() + 1);
vector<Node *> nodes = vector<Node *>(arr.size() + 1, nullptr);
for (size_t i = 1; i <= arr.size(); i++) {
nodes[i] = new Node(static_cast<int>(i));
}
Expand Down Expand Up @@ -52,4 +53,23 @@ vector<vector<int>> NodeNeighborsToJsonArray(Node *root) {
visited.insert(root->val);
dfs(root, ans, visited);
return ans;
}

void DeleteGraph(Node* root) {
if (!root) return;
std::unordered_set<Node*> visited;
std::queue<Node*> q;
q.push(root);
visited.insert(root);
while (!q.empty()) {
Node* node = q.front();
q.pop();
for (Node* neighbor : node->neighbors) {
if (neighbor && !visited.count(neighbor)) {
visited.insert(neighbor);
q.push(neighbor);
}
}
delete node;
}
}
3 changes: 2 additions & 1 deletion cpp/models/NodeNeighbors.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ class Node {
}
};

Node *JsonArrayToNodeNeighbors(vector<vector<int>> arr);
Node *JsonArrayToNodeNeighbors(const vector<vector<int>>& arr);
vector<vector<int>> NodeNeighborsToJsonArray(Node *root);
void DeleteGraph(Node* root);

#endif //LEETCODE_NODENEIGHBORS_H
4 changes: 4 additions & 0 deletions cpp/models/NodeRandom.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ class Node {
next = nullptr;
random = nullptr;
}

~Node() {
delete next; // Automatically delete the next node to avoid memory leaks
}
};

Node* JsonArrayToNodeRandom(json arr);
Expand Down
6 changes: 6 additions & 0 deletions cpp/models/TreeNodeNext.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ class Node {

Node(int _val, Node* _left, Node* _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}

~Node() {
delete left;
delete right;
// next is not deleted here because it may point to another Node in the same tree
}
};

Node *JsonArrayToTreeNodeNext(json arr);
Expand Down
2 changes: 1 addition & 1 deletion daily-problems.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"daily": "2767",
"daily": "1932",
"plans": ["1", "problems", "LCR_115", "problems"]
}
27 changes: 15 additions & 12 deletions problems/problems_105/Solution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,20 @@ class Solution {
};

json leetcode::qubh::Solve(string input_json_values) {
vector<string> inputArray;
size_t pos = input_json_values.find('\n');
while (pos != string::npos) {
inputArray.push_back(input_json_values.substr(0, pos));
input_json_values = input_json_values.substr(pos + 1);
pos = input_json_values.find('\n');
}
inputArray.push_back(input_json_values);
vector<string> inputArray;
size_t pos = input_json_values.find('\n');
while (pos != string::npos) {
inputArray.push_back(input_json_values.substr(0, pos));
input_json_values = input_json_values.substr(pos + 1);
pos = input_json_values.find('\n');
}
inputArray.push_back(input_json_values);

Solution solution;
vector<int> preorder = json::parse(inputArray.at(0));
vector<int> inorder = json::parse(inputArray.at(1));
return TreeNodeToJsonArray(solution.buildTree(preorder, inorder));
Solution solution;
vector<int> preorder = json::parse(inputArray.at(0));
vector<int> inorder = json::parse(inputArray.at(1));
TreeNode *res_ptr = solution.buildTree(preorder, inorder);
json final_ans = TreeNodeToJsonArray(res_ptr);
delete res_ptr;
return final_ans;
}
28 changes: 15 additions & 13 deletions problems/problems_114/Solution.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,20 @@ class Solution {
};

json leetcode::qubh::Solve(string input_json_values) {
vector<string> inputArray;
size_t pos = input_json_values.find('\n');
while (pos != string::npos) {
inputArray.push_back(input_json_values.substr(0, pos));
input_json_values = input_json_values.substr(pos + 1);
pos = input_json_values.find('\n');
}
inputArray.push_back(input_json_values);
vector<string> inputArray;
size_t pos = input_json_values.find('\n');
while (pos != string::npos) {
inputArray.push_back(input_json_values.substr(0, pos));
input_json_values = input_json_values.substr(pos + 1);
pos = input_json_values.find('\n');
}
inputArray.push_back(input_json_values);

Solution solution;
json root_array = json::parse(inputArray.at(0));
TreeNode *root = JsonArrayToTreeNode(root_array);
solution.flatten(root);
return TreeNodeToJsonArray(root);
Solution solution;
json root_array = json::parse(inputArray.at(0));
TreeNode *root = JsonArrayToTreeNode(root_array);
solution.flatten(root);
json final_ans = TreeNodeToJsonArray(root);
delete root;
return final_ans;
}
86 changes: 86 additions & 0 deletions problems/problems_133/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// go:build ignore
#include <queue>

#include "cpp/common/Solution.h"
#include "cpp/models/NodeNeighbors.h"

using namespace std;
using json = nlohmann::json;

/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/

class Solution {
public:
Node *cloneGraph(Node *node) {
if (node == nullptr) {
return node;
}

unordered_map<Node *, Node *> visited;

// 将题目给定的节点添加到队列
queue<Node *> Q;
Q.push(node);
// 克隆第一个节点并存储到哈希表中
visited[node] = new Node(node->val);

// 广度优先搜索
while (!Q.empty()) {
// 取出队列的头节点
auto n = Q.front();
Q.pop();
// 遍历该节点的邻居
for (auto &neighbor : n->neighbors) {
if (visited.find(neighbor) == visited.end()) {
// 如果没有被访问过,就克隆并存储在哈希表中
visited[neighbor] = new Node(neighbor->val);
// 将邻居节点加入队列中
Q.push(neighbor);
}
// 更新当前节点的邻居列表
visited[n]->neighbors.emplace_back(visited[neighbor]);
}
}

return visited[node];
}
};

json leetcode::qubh::Solve(string input_json_values) {
vector<string> inputArray;
size_t pos = input_json_values.find('\n');
while (pos != string::npos) {
inputArray.push_back(input_json_values.substr(0, pos));
input_json_values = input_json_values.substr(pos + 1);
pos = input_json_values.find('\n');
}
inputArray.push_back(input_json_values);

Solution solution;
vector<vector<int>> node_arrays = json::parse(inputArray.at(0));
Node *node = JsonArrayToNodeNeighbors(node_arrays);
Node *res_ptr = solution.cloneGraph(node);
json final_ans = NodeNeighborsToJsonArray(res_ptr);
DeleteGraph(node); // Delete the graph to prevent memory leak
DeleteGraph(res_ptr); // Delete the graph to prevent memory leak
return final_ans;
}
38 changes: 38 additions & 0 deletions problems/problems_133/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package problems.problems_133;

import com.alibaba.fastjson.JSON;
import java.util.*;
import qubhjava.BaseSolution;
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> neighbors;
public Node() {
val = 0;
neighbors = new ArrayList<Node>();
}
public Node(int _val) {
val = _val;
neighbors = new ArrayList<Node>();
}
public Node(int _val, ArrayList<Node> _neighbors) {
val = _val;
neighbors = _neighbors;
}
}
*/

import qubhjava.models.node.neighbors.Node;

public class Solution extends BaseSolution {
public Node cloneGraph(Node node) {

}

@Override
public Object solve(String[] inputJsonValues) {
Node node = Node.ArrayToNodeNeighbors(jsonArrayToInt2DArray(inputJsonValues[0]));
return JSON.toJSON(Node.NodeNeighborsToArray(cloneGraph(node)));
}
}
2 changes: 1 addition & 1 deletion problems/problems_133/problem.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 133. Clone Graph
# 133. Clone Graph

<p>Given a reference of a node in a <strong><a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph" target="_blank">connected</a></strong> undirected graph.</p>

Expand Down
Loading