Я пытаюсь получить ввод с клавиатуры в выражении постфикса и помещаю его в дерево. Однако каждый символ является новым деревом и помещается в стек. Всякий раз, когда он достигает оператора, стек выталкивается, а левый и правый символ размещается слева и справа от узла, содержащего оператор. Однако, когда я пытаюсь выскочить из стека, я получаю исключение NullPointerException?
Main
import java.util.Scanner;
public class main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the postfix expression");
String expression = input.nextLine();
StackTree st = new StackTree();
st.setUp(expression);
}
}
Дерево
public class Tree
{
private char item;
private Tree left;
private Tree right;
Tree(char item)
{
this.item=item;
}
public char getItem()
{
return this.item;
}
public Tree getLeft()
{
return this.left;
}
public Tree getRight()
{
return this.right;
}
public void setLeft(Tree left)
{
this.left=left;
}
public void setRight(Tree right)
{
this.right=right;
}
}
StackTree
public class StackTree
{
private Tree item;
private StackTree prev;
StackTree()
{
}
StackTree(Tree item)
{
this.item=item;
}
public void push(Tree item)
{
StackTree curr = new StackTree(item);
if(prev==null) // if prev is empty, set it equal to the curr
{
prev = curr;
}
else // otherwise make the currs previous set to the last node in the stack, and make the last node in the stack the new node
{
curr.setPrev(prev);
prev = curr;
}
}
public Tree pop() // pops a node from the stack and returns its tree
{
if(prev == null)
{
return null;
}
else
{
prev = prev.getPrev();
return prev.getRoot();
}
}
public boolean isOperator(char op) // checks if the character is an operator
{
return (op == '+' || op == '-' || op == '/' || op == '*' || op == '^') ? true : false;
}
public void displayInfix(Tree root)
{
if(root != null)
{
if(root.getLeft() != null && root.getRight() != null)
{
System.out.print("(");
}
displayInfix(root.getLeft());
System.out.print(root.getItem());
displayInfix(root.getRight());
if(root.getLeft() != null && root.getRight() != null)
{
System.out.print("(");
}
}
}
public StackTree getPrev() // returns previous address
{
return this.prev;
}
public void setPrev(StackTree prev) // sets the next previous address
{
this.prev=prev;
}
public Tree getRoot() // returns the tree
{
return this.item;
}
public Tree setUp(String piece)
{
for(int i = 0; i < piece.length(); i++)
{
prev = new StackTree();
item = new Tree(piece.charAt(i));
if(isOperator(piece.charAt(i))) // if theres an operator in the spring, pop the two nodes in the stack
{
item.setRight(prev.pop()); // pop the stack and set it to the right
item.setLeft(prev.pop()); // pop the stack and set it to the left
prev.push(item); // push the tree onto the stack
}
else // if the
{
prev.push(item);
}
}
item = prev.pop();
return item;
}
}