From e98832db0e1292bb6bb952aab1905e9db1aa5fd2 Mon Sep 17 00:00:00 2001 From: Arti Zirk Date: Mon, 31 Oct 2016 17:04:35 +0200 Subject: [PATCH] home5 --- src/Node.java | 68 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 65 insertions(+), 3 deletions(-) diff --git a/src/Node.java b/src/Node.java index a8bcff8..8015c64 100644 --- a/src/Node.java +++ b/src/Node.java @@ -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 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) {