Removing a field from a Linked List (MatLab) -


i have 1 way linked list:

s=struct('field1', value1, 'field2', value2, 'field3', value3, 'next',[]) s=struct('field1', value3, 'field2', value5, 'field3', value6, 'next', s) 

how remove 'next' field linked list becomes standard structure array, so?

s(1)=struct('field1', value1, 'field2', value2, 'field3', value3) s(2)=struct('field1', value3, 'field2', value5, 'field3', value6) 

i have tried rmfield command 1x1 structure array, want, in example, 1x2 structure array.

you want first aggregate of structs together. use recursive function this. can call rmfield on array of structs. combine 2 @ same time.

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 comments, since appending data output, can slow larger lists. determine expected output size , fill within loop.

this approach allow pre-allocate output.

function output = flattenlist(s)      % determine how big make output     tmp = s;     count = 1;     while ~isempty(tmp.next)         count = count + 1;         tmp = tmp.next;     end           % pre-allocate 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 

Comments