Tree from nesting levels: Difference between revisions
Content added Content deleted
(Tree from nesting levels in FreeBASIC) |
(New post.) |
||
Line 1,208: | Line 1,208: | ||
│└─────┴─┴─────┴─┘│ │ │ |
│└─────┴─┴─────┴─┘│ │ │ |
||
└─────────────────┴─┴─────┘</syntaxhighlight> |
└─────────────────┴─┴─────┘</syntaxhighlight> |
||
=={{header|Java}}== |
|||
<syntaxhighlight lang="java"> |
|||
import java.util.ArrayList; |
|||
import java.util.Arrays; |
|||
import java.util.List; |
|||
import java.util.Stack; |
|||
public final class TreeNestingLevels { |
|||
public static void main(String[] args) { |
|||
List<List<Integer>> lists = List.of( |
|||
Arrays.asList(), |
|||
Arrays.asList( 1, 2, 4 ), |
|||
Arrays.asList( 3, 1, 3, 1 ), |
|||
Arrays.asList( 1, 2, 3, 1 ), |
|||
Arrays.asList( 3, 2, 1, 3 ), |
|||
Arrays.asList( 3, 3, 3, 1, 1, 3, 3, 3 ) |
|||
); |
|||
for ( List<Integer> list : lists ) { |
|||
List<Object> tree = createTree(list); |
|||
System.out.println(list + " --> " + tree); |
|||
} |
|||
} |
|||
private static List<Object> createTree(List<Integer> list) { |
|||
List<Object> tree = new ArrayList<Object>(); |
|||
Stack<List<Object>> stack = new Stack<List<Object>>(); |
|||
stack.push(tree); |
|||
for ( int item : list ) { |
|||
while ( item != stack.size() ) { |
|||
if ( item > stack.size() ) { |
|||
List<Object> innerTree = new ArrayList<Object>(); |
|||
stack.peek().add(innerTree); |
|||
stack.push(innerTree); |
|||
} else { |
|||
stack.pop(); |
|||
} |
|||
} |
|||
stack.peek().add(item); |
|||
} |
|||
return tree; |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{ out }} |
|||
<pre> |
|||
[] --> [] |
|||
[1, 2, 4] --> [1, [2, [[4]]]] |
|||
[3, 1, 3, 1] --> [[[3]], 1, [[3]], 1] |
|||
[1, 2, 3, 1] --> [1, [2, [3]], 1] |
|||
[3, 2, 1, 3] --> [[[3], 2], 1, [[3]]] |
|||
[3, 3, 3, 1, 1, 3, 3, 3] --> [[[3, 3, 3]], 1, 1, [[3, 3, 3]]] |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |