This commit is contained in:
Arti Zirk 2016-10-31 17:04:35 +02:00
parent 997c80fe68
commit e98832db0e
1 changed files with 65 additions and 3 deletions

View File

@ -8,15 +8,77 @@ public class Node {
private Node nextSibling;
Node (String n, Node d, Node r) {
// TODO!!! Your constructor here
this.name = n;
this.firstChild = d;
this.nextSibling = r;
}
public static Node parsePostfix (String s) {
return null; // TODO!!! return the root
if (s.contains(",,")) {
throw new RuntimeException("double commas");
} else if (s.contains("\t")) {
throw new RuntimeException("tab char");
} else if (s.contains("()")) {
throw new RuntimeException("empty subtree");
} else if (s.contains(" ")) {
throw new RuntimeException("space");
} else if (s.contains("((") && s.contains("))")) {
throw new RuntimeException("Brackets");
} else if (s.contains(",") && !(s.contains("(") && s.contains(")"))) {
throw new RuntimeException("two roots");
}
String[] tokens = s.split("");
Stack<Node> stack = new Stack();
Node node = new Node(null, null, null);
boolean replacingRoot = false;
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].trim();
if (token.equals("(")) {
if (replacingRoot) {
throw new RuntimeException("Trying to replace root");
}
stack.push(node);
node.firstChild = new Node(null, null, null);
node = node.firstChild;
if (tokens[i+1].trim().equals(",")) {
throw new RuntimeException("comma after node");
}
} else if (token.equals(")")) {
node = stack.pop();
if (stack.size() == 0) {
replacingRoot = true;
}
} else if (token.equals(",")) {
if (replacingRoot) {
throw new RuntimeException("Trying to replace root");
}
node.nextSibling = new Node(null, null, null);
node = node.nextSibling;
} else {
if (node.name == null) {
node.name = token;
} else {
node.name += token;
}
}
}
return node;
}
public String leftParentheticRepresentation() {
return ""; // TODO!!! return the string without spaces
StringBuilder sb = new StringBuilder();
sb.append(this.name);
if (this.firstChild != null) {
sb.append("(");
sb.append(this.firstChild.leftParentheticRepresentation());
sb.append(")");
}
if (this.nextSibling != null) {
sb.append(",");
sb.append(this.nextSibling.leftParentheticRepresentation());
}
return sb.toString();
}
public static void main (String[] param) {