Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Document management system - build unordered list (table of contents) recursively
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { public static void main(String args[]) { List<Heading> headings = new ArrayList<>(); headings.add(new Heading(1,"America")); headings.add(new Heading(2,"North America")); headings.add(new Heading(3,"United States")); headings.add(new Heading(2,"South America")); headings.add(new Heading(3,"Brazil")); headings.add(new Heading(3,"Urugway")); Node outline = toOutline(headings); String html = toHtml(outline); System.out.println(html); } /////////// BEGIN EDITABLE ////////////// private static Node toOutline(List<Heading> headings) { // Implement this function. Sample code below builds an // outline of only the first heading. Node root = new Node(new Heading(0, "")); addChildren(root,headings,0); return root; } private static void addChildren(Node node,List<Heading> headings,int i){ int curr_weight = node.heading.weight; while(i<headings.size()){ if(headings.get(i).weight==curr_weight || headings.get(i).weight==curr_weight-1) return; if(headings.get(i).weight==curr_weight+1){ Node child = new Node(headings.get(i)); node.children.add(child); addChildren(child,headings,i+1); } i++; } } /////////// END EDITABLE ////////////// private static Heading parse(String record) { String[] parts = record.split(" ", 2); int weight = Integer.parseInt(parts[0].substring(1)); Heading heading = new Heading(weight, parts[1].trim()); return heading; } private static String toHtml(Node node) { StringBuilder buf = new StringBuilder(); if (!node.heading.text.isEmpty()) { buf.append(node.heading.text); buf.append("\n"); } Iterator<Node> iter = node.children.iterator(); if (iter.hasNext()) { buf.append("<ul>"); while (iter.hasNext()) { Node child = iter.next(); buf.append("<li>"); buf.append(toHtml(child)); buf.append("</li>"); if (iter.hasNext()) { buf.append("\n"); } } buf.append("</ul>"); } return buf.toString(); } } class Heading { protected int weight; protected String text; public Heading(int weight, String text) { this.weight = weight; this.text = text; } } class Node { protected Heading heading; protected List<Node> children; public Node(Heading heading) { this.heading = heading; this.children = new ArrayList<>(); } }
run
|
edit
|
history
|
help
0
boundary vs core
exp 4
Item battle rolyal
forloop1
Fraction implementation using oops in java
1.6
Complex Number implementation using oops java
javaLP
bookstore
MergeSort