algorithm - Flatten out a list in java -
i asked question in interview
given hypothetical list in java that, along holding integer content, may hold list of similar type
example: [1,3,5,[6,7],8,9,10,[11,13,15,[16,17,[18,19]]],20]
output should be:
[1,3,5,6,7,8,9,10,11,13,15,16,17,18,19,20]
easy thought! came recursive solution solved problem! or not?
the interviewer said sublists go down depths , hence may result in stackoverflow error!
i tried coming non recursive solution, couldn't. tell non recursive solution might be?
you can use linkedlist stack.
public static list<object> flattennonrecursive(list<object> list) { list<object> result = new arraylist<>(); linkedlist<object> stack = new linkedlist<>(list); while (!stack.isempty()) { object e = stack.pop(); if (e instanceof list<?>) stack.addall(0, (list<?>)e); else result.add(e); } return result; } public static list<object> list(object... args) { return arrays.aslist(args); } public static void main(string[] args) { list<object> list = list(1, 3, 5, list(6, 7), 8, 9, 10, list(11, 13, 15, list(16, 17, list(18, 19))), 20); system.out.println("flatten=" + flattennonrecursive(list)); }
result
flatten=[1, 3, 5, 6, 7, 8, 9, 10, 11, 13, 15, 16, 17, 18, 19, 20]
Comments
Post a Comment