I have a one way linked list:
我有一个单向链表:
s=struct('field1', value1, 'field2', value2, 'field3', value3, 'next',[])
s=struct('field1', value3, 'field2', value5, 'field3', value6, 'next', s)
How do I remove the 'next' field so that my linked list becomes a standard structure array, like so?
如何删除“下一个”字段,以便我的链表成为标准结构数组,如此?
s(1)=struct('field1', value1, 'field2', value2, 'field3', value3)
s(2)=struct('field1', value3, 'field2', value5, 'field3', value6)
I have tried the rmfield command but I get a 1x1 structure array, but I want, in this example, a 1x2 structure array.
我已经尝试了rmfield命令,但我得到了一个1x1结构数组,但在这个例子中,我想要一个1x2结构数组。
1 个解决方案
#1
1
You will want to first aggregate all of your structs together. You could use a recursive function to do this. Then you can call rmfield
on the array of structs. You could also even combine the two at the same time.
您将希望首先将所有结构聚合在一起。您可以使用递归函数来执行此操作。然后你可以在结构数组上调用rmfield。你甚至可以同时将两者结合起来。
function S = flattenList(S)
if isempty(S.next)
S = rmfield(S, 'next');
else
S = cat(2, rmfield(S, 'next'), flattenList(S.next));
end
end
As pointed out in the comments, since we are constantly appending data to the output, it can be slow for larger lists. We could determine the expected output size and then fill it within the loop.
正如评论中所指出的,由于我们不断地将数据附加到输出,因此对于较大的列表来说可能会很慢。我们可以确定预期的输出大小,然后在循环中填充它。
This approach would allow you to pre-allocate the output.
此方法允许您预分配输出。
function output = flattenList(S)
% Determine how big to make the output
tmp = S;
count = 1;
while ~isempty(tmp.next)
count = count + 1;
tmp = tmp.next;
end
% Pre-allocate the output
output = repmat(rmfield(S(1), 'next'), [1 count]);
tmp = S;
count = 1;
while true
output(count) = rmfield(tmp, 'next');
if isempty(tmp.next)
break;
else
tmp = S.next;
end
end
end
#1
1
You will want to first aggregate all of your structs together. You could use a recursive function to do this. Then you can call rmfield
on the array of structs. You could also even combine the two at the same time.
您将希望首先将所有结构聚合在一起。您可以使用递归函数来执行此操作。然后你可以在结构数组上调用rmfield。你甚至可以同时将两者结合起来。
function S = flattenList(S)
if isempty(S.next)
S = rmfield(S, 'next');
else
S = cat(2, rmfield(S, 'next'), flattenList(S.next));
end
end
As pointed out in the comments, since we are constantly appending data to the output, it can be slow for larger lists. We could determine the expected output size and then fill it within the loop.
正如评论中所指出的,由于我们不断地将数据附加到输出,因此对于较大的列表来说可能会很慢。我们可以确定预期的输出大小,然后在循环中填充它。
This approach would allow you to pre-allocate the output.
此方法允许您预分配输出。
function output = flattenList(S)
% Determine how big to make the output
tmp = S;
count = 1;
while ~isempty(tmp.next)
count = count + 1;
tmp = tmp.next;
end
% Pre-allocate the output
output = repmat(rmfield(S(1), 'next'), [1 count]);
tmp = S;
count = 1;
while true
output(count) = rmfield(tmp, 'next');
if isempty(tmp.next)
break;
else
tmp = S.next;
end
end
end