[英]c++ shared pointer linked list
what is the correct way of creating a linked list out of an array The type declaration is the following从数组中创建链表的正确方法是什么类型声明如下
template<typename T>
struct ListNode {
public:
T data;
shared_ptr<ListNode<T>> next;
ListNode() { }
ListNode(T data, shared_ptr<ListNode<T>> next) {
this->data = data;
this->next = next;
}
};
the array structure is the following [value1, index1, value2, index2, ... , valueN] on even position goes value, next goes relative index of the next value in the array数组结构如下 [value1, index1, value2, index2, ... , valueN] 在偶数位置是值,接下来是数组中下一个值的相对索引
example: [1,1,2,2,3,1]例如:[1,1,2,2,3,1]
should create the following linked_list: node(val=1,idx=0) -> node(val=2,idx=1) -> node(val=3,idx=2) -> node(val=2,idx=1) -> ...应该创建以下链接列表: node(val=1,idx=0) -> node(val=2,idx=1) -> node(val=3,idx=2) -> node(val=2,idx= 1) -> ...
My current buggy implementation is the following:我目前的错误实现如下:
shared_ptr<ListNode<int>> convert(vector<int> value) {
vector<shared_ptr<ListNode<int>>> nodes;
for (int i = 0; i < value.size(); i += 2) {
shared_ptr<ListNode<int>> node = make_shared<ListNode<int>>();
node->data = value[i];
nodes.push_back(node);
}
for (int i = 1; i < value.size(); i += 2) {
shared_ptr<ListNode<int>> node = nodes[floor((i - 1) / 2)];
int nextIndex = value[i];
if (nextIndex >= 0) {
shared_ptr<ListNode<int>> nextNode = nodes[nextIndex];
node->next = nextNode;
}
}
return nodes.empty() ? nullptr : nodes[0];
}
After returning from this function I have memory issues.从这个函数返回后,我遇到了内存问题。 Any code or links will be appreciated.
任何代码或链接将不胜感激。 Thanks.
谢谢。
首先,尝试make_shared<ListNode<int>>()
而不是make_unique<ListNode<int>>()
因为您在其他任何地方都使用shared_ptr
。
The trick here is to keep a pointer to the last element of your list, and incrementing it in each iteration of the loop.这里的技巧是保持一个指向列表最后一个元素的指针,并在循环的每次迭代中递增它。
shared_ptr<ListNode<int>> convert(vector<int> values) {
shared_ptr<ListNode<int>> head;
if(values.size() == 0) return head;
head = shared_ptr<ListNode<int>>(new ListNode<int>());
ListNode<int> *node = head.get();
node->data = values[0];
for (int i = 1; i < values.size(); i++) {
node->next = shared_ptr<ListNode<int>>(new ListNode<int>());
node->next->data = values[i];
node = node->next.get();
}
return head;
}
int main() {
vector<int> vec = {1, 2, 3, 4};
shared_ptr<ListNode<int>> list = convert(vec);
cout
<<list->data<<" "
<<list->next->data<<" "
<<list->next->next->data<<" "
<<list->next->next->next->data<<endl;
return 0;
}
output: 1 2 3 4
.输出:
1 2 3 4
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.