Стек с двойной связью Java с использованием ADT для Infix to Postfix - PullRequest
0 голосов
/ 11 апреля 2020

Я пытаюсь преобразовать инфикс в постфикс, используя ADT в формате двойного связанного списка, но продолжаю получать разные ошибки для разных строковых входов для преобразования. Если на это ответили, я прошу прощения. Я искал бесконечно, и мне не повезло понять, что я делаю неправильно (что я уверен, это много). Спасибо за любую помощь, спасибо.

import java.util.Scanner;

public class DoublyLinkedStack<T> implements StackInterface<T> {

    private double value;
    private int numberOfElements = 0;
    private Node<T> head;
    private Node<T> tail;
    private class Node<T>
    {   private T data;
        private Node<T> prevNode = null;
        private Node<T> nextNode = null;
        public Node(T data) { this.data = data; }
        public Node(T data, Node<T> prevNode, Node<T> nextNode)
        {   this.data = data;
            this.prevNode = prevNode;
            this.nextNode = nextNode;
        }
        public T getData() { return data; }
        public void setData(T data) { this.data = data; }
        public Node<T> getPrevNode() { return prevNode; }
        public void setPrevNode(Node<T> prevNode) { this.prevNode = prevNode; }
        public Node<T> getNextNode() { return nextNode; }
        public void setNextNode(Node<T> nextNode) { this.nextNode = nextNode; }
    }
    public T peek() { return head.getData(); }
    public T pop()
    {   T data = head.getData();
        head = head.getNextNode();
        numberOfElements--;
        return data;
    }
    public void push(T entry)
    {   Node<T> anchor = new Node<T>(entry);
        if (head == null)
        { head = anchor; }
        else
        {   anchor.setNextNode(head);
            head = anchor;
            numberOfElements++;
        }
    }
    public T dataIndex(int index)
    {   if (index > numberOfElements)
        {   System.out.println("Index too large, will cause infinite loop.");
            return null;
        }
        else
        {   tail = head;
            for (int i = 0; i < index; i++)
            { tail = tail.getNextNode(); }
            return tail.getData();
        }
    }
    public int getCurrentSize() { return numberOfElements; }
    public boolean order(String first, String second)
    { switch (first)
        { case "+":
            case "-": { return false; }
            case "*":
                switch (second)
                {   case "+":
                    case "-":
                    case "/": { return true; }
                    default: { return false; }
                }
            case "^":
                switch (second)
                {   case "+":
                    case "-":
                    case "*":
                    case "/": { return true; }
                    default: { return false; }
                }
            default: { return false; }
        }
    }
    public double postfixCalculator(String input)
    {   double first;
        double second;
        double finish;
        DoublyLinkedStack<Double> calc = new DoublyLinkedStack<Double>();
        String[] split = input.split(" ");
        int i = 0;
        String simpson;
        while (i < split.length)
        {   simpson = split[i];
            switch(simpson)
            { case "+":
                {   first = calc.pop();
                    second = calc.pop();
                    finish = first + second;
                    calc.push(finish);
                    break;
                }
                case "-":
                {   first = calc.pop();
                    second = calc.pop();
                    finish = second - first;
                    calc.push(finish);
                    break;
                }
                case "*":
                {   first = calc.pop();
                    second = calc.pop();
                    finish = first * second;
                    calc.push(finish);
                    break;
                }
                case "/":
                {   first = calc.pop();
                    second = calc.pop();
                    finish = second/first;
                    calc.push(finish);
                    break;
                }
                case "^":
                {   first = calc.pop();
                    second = calc.pop();
                    finish = Math.pow(second, first);
                    calc.push(finish);
                    break;
                }
                default: { calc.push(Double.parseDouble(simpson)); }
                i++;
            }
        } return calc.peek();
    }
    @Override
    public boolean isEmpty() {
        // TODO Auto-generated method stub
        return false;
    }
    @Override
    public void clear() {
        // TODO Auto-generated method stub

    }

    public static void main(String[] args) {
        String expression;
        String postfix = null;
        Scanner console = new Scanner(System.in);
        System.out.println("Enter Desired Expression:");
        expression = console.nextLine();
        String[] split = expression.split(" ");
        DoublyLinkedStack<String> stack = new DoublyLinkedStack<String>();
        for (int i = 0; i < split.length; i++) {
            if (postfix == null) {
                postfix = ("" + split[i]);
            } else {
                postfix = postfix + " " + split[i];
            }
            if (split[i].equals(")")) {
                while (!stack.peek().equals("(")) {
                    postfix = postfix + " " + stack.pop();
                }
                stack.pop();
            } else if (split[i].equals("]")) {
                while (!stack.peek().equals("[")) {
                    postfix = postfix + " " + stack.pop();
                }
                stack.pop();
            } else if (split[i].equals("}")) {
                while (!stack.peek().equals("{")) {
                    postfix = postfix + " " + stack.pop();
                }
                stack.pop();
            } else {
                if (stack.getCurrentSize() == 0) {
                    stack.push(split[i]);
                } else {
                    while (stack.order(stack.dataIndex(stack.getCurrentSize() - i), split[i]) == true) {
                        postfix = postfix + " " + stack.pop();
                    }
                    stack.push(split[i]);
                }
            }
        }
        while (stack.getCurrentSize() != 1) {
            postfix = postfix + " " + stack.pop();
        }
        System.out.println("Postfix:" + postfix + "\nResult:" + stack.postfixCalculator(postfix));
    }
}


public interface StackInterface <T> {

    public void push (T newEntry);
    public T pop();
    public T peek();
    public boolean isEmpty();
    public void clear();
}

Ответы [ 2 ]

0 голосов
/ 19 апреля 2020

publi c Класс DoublyLinkedStack реализует StackInterface {

private class Node<T> {

    private T nodeData;
    private Node<T> prevNode = null;
    private Node<T> nextNode = null;

    public Node(T nodeData) {
        this.nodeData = nodeData;
    }

    public T getNodeData() {
        return nodeData;
    }

    public Node<T> getPrevNode() {
        return prevNode;
    }

    public void setPrevNode(Node<T> prevNode) {
        this.prevNode = prevNode;
    }

    public Node<T> getNextNode() {
        return nextNode;
    }

    public void setNextNode(Node<T> nextNode) {
        this.nextNode = nextNode;
    }
}

private int numberOfElements = 0;
private Node<T> head = null;
private Node<T> tail = null;

// Constructor
public DoublyLinkedStack() {
}

// isEmpty method
public boolean isEmpty() {
    if (numberOfElements == 0) {
        return true;

    } else {
        return false;
    }
}

// getCurrentSize method
public int getCurrentSize() {
    return numberOfElements;
}

public T getHead() {
    return head.getNodeData();
}

public T removeHead() {
    if (head == null) {
        return null;
    }

    Node<T> temp = head;

    if (numberOfElements == 1) {
        head = null;
        tail = null;

    } else {

        head = head.getNextNode();
        head.setPrevNode(null);
    }
    numberOfElements--;
    return temp.getNodeData();
}

public void Push(T input) {

    Node<T> newNode = new Node<T>(input);

    if (tail == null) {
        head = newNode;
        tail = newNode;

    } else {
        newNode.setPrevNode(tail);
        tail.setNextNode(newNode);
        tail = newNode;
    }
    numberOfElements++;
}

public T Peek() {
    return tail.getNodeData();
}

public T Pop() {

    if (tail == null) {
        return null;
    }

    Node<T> temp = tail;

    if (numberOfElements == 1) {
        head = null;
        tail = null;

    } else {
        tail = tail.getPrevNode();
        tail.setNextNode(null);
    }
    numberOfElements--;
    return temp.getNodeData();
}

public void clear() {

    head = null;
    tail = null;
    numberOfElements = 0;
}

public void printList() {

    Node<T> temp;
    System.out.print("Postfix: ");
    temp = head;

    while (temp != null) {
        System.out.print(temp.getNodeData() + " ");
        temp = temp.getNextNode();
    }
}

public interface StackInterface <T> {

    public void Push (T newEntry);
    public T Pop();
    public T Peek();
    public boolean isEmpty();
    public void clear();
}

}

0 голосов
/ 19 апреля 2020

import java .util.Scanner;

publi c class Main {

public static void main(String[] args) {

    String[] infix;
    Scanner keyboard = new Scanner(System.in);
    String userInput = keyboard.nextLine();

    infix = userInput.split(" ");

    DoublyLinkedStack<String> tempOperand = new DoublyLinkedStack();
    DoublyLinkedStack<String> tempOperator = new DoublyLinkedStack();

    for (int k = 0; k < infix.length; k++) {

        switch (infix[k]) {

        case "-":
            while (openParenths(tempOperator) == false) {

                String temp;
                temp = tempOperator.Pop();
                tempOperand.Push(temp);

                if (toCheckForNull(tempOperator) == false) {
                    break;
                }
            }
            tempOperator.Push(infix[k]);
            break;

        case "+":
            while (openParenths(tempOperator) == false) {

                String temp;
                temp = tempOperator.Pop();
                tempOperand.Push(temp);

                if (toCheckForNull(tempOperator) == false) {
                    break;
                }
            }
            tempOperator.Push(infix[k]);
            break;

        case "/":
            while (openParenths(tempOperator) == false && tempOperator.Peek().equals("-") == false
                    && tempOperator.Peek().equals("+") == false) {

                String temp;
                temp = tempOperator.Pop();
                tempOperand.Push(temp);

                if (toCheckForNull(tempOperator) == false) {
                    break;
                }
            }
            tempOperator.Push(infix[k]);
            break;

        case "*":
            while (openParenths(tempOperator) == false && tempOperator.Peek().equals("-") == false
                    && tempOperator.Peek().equals("+") == false) {

                String temp;
                temp = tempOperator.Pop();
                tempOperand.Push(temp);

                if (toCheckForNull(tempOperator) == false) {
                    break;
                }
            }
            tempOperator.Push(infix[k]);
            break;

        case "^":
            while (openParenths(tempOperator) == false && tempOperator.Peek().equals("-") == false
                    && tempOperator.Peek().equals("+") == false && tempOperator.Peek().equals("/") == false
                    && tempOperator.Peek().equals("*") == false) {

                String temp;
                temp = tempOperator.Pop();
                tempOperand.Push(temp);

                if (toCheckForNull(tempOperator) == false) {
                    break;
                }
            }
            tempOperator.Push(infix[k]);
            break;

        case ")":
            while (tempOperator.Peek().equals("(") == false) {

                String temp;
                temp = tempOperator.Pop();
                tempOperand.Push(temp);

                if (toCheckForNull(tempOperator) == false) {
                    break;
                }
            }
            tempOperator.Pop();
            break;

        case "]":
            while (tempOperator.Peek().equals("[") == false) {

                String temp;
                temp = tempOperator.Pop();
                tempOperand.Push(temp);

                if (toCheckForNull(tempOperator) == false) {
                    break;
                }
            }
            tempOperator.Pop();
            break;

        case "}":
            while (tempOperator.Peek().equals("{") == false) {

                String temp;
                temp = tempOperator.Pop();
                tempOperand.Push(temp);

                if (toCheckForNull(tempOperator) == false) {
                    break;
                }
            }
            tempOperator.Pop();
            break;

        default:

            if (infix[k].equals("(") == true || infix[k].equals("[") == true || infix[k].equals("{") == true) {
                tempOperator.Push(infix[k]);

            } else {

                tempOperand.Push(infix[k]);
            }
        }
    }

    while (tempOperator.getCurrentSize() != 0) {
        String temp;
        temp = tempOperator.Pop();
        tempOperand.Push(temp);
    }

    tempOperand.printList();
    double var = tempOperand.getCurrentSize();

    for (int i = 0; i < var; i++) {

        double firstOp, secondOp, solution;

        switch (tempOperand.getHead()) {

        case "-":

            firstOp = Double.parseDouble(tempOperator.Pop());
            secondOp = Double.parseDouble(tempOperator.Pop());
            solution = secondOp - firstOp;
            tempOperator.Push(String.valueOf(solution));
            tempOperand.removeHead();
            break;

        case "+":

            firstOp = Double.parseDouble(tempOperator.Pop());
            secondOp = Double.parseDouble(tempOperator.Pop());
            solution = secondOp + firstOp;
            tempOperator.Push(String.valueOf(solution));
            tempOperand.removeHead();
            break;

        case "*":

            firstOp = Double.parseDouble(tempOperator.Pop());
            secondOp = Double.parseDouble(tempOperator.Pop());
            solution = secondOp * firstOp;
            tempOperator.Push(String.valueOf(solution));
            tempOperand.removeHead();
            break;

        case "/":

            firstOp = Double.parseDouble(tempOperator.Pop());
            secondOp = Double.parseDouble(tempOperator.Pop());
            solution = secondOp / firstOp;
            tempOperator.Push(String.valueOf(solution));
            tempOperand.removeHead();
            break;

        case "^":

            firstOp = Double.parseDouble(tempOperator.Pop());
            secondOp = Double.parseDouble(tempOperator.Pop());
            solution = Math.pow(secondOp, firstOp);
            tempOperator.Push(String.valueOf(solution));
            tempOperand.removeHead();
            break;

        default:
            tempOperator.Push(tempOperand.getHead());
            tempOperand.removeHead();

        }
    }

    System.out.println();
    System.out.print("Postfix solution: ");
    System.out.println(tempOperator.Peek());
}

public static boolean toCheckForNull(DoublyLinkedStack isItNull) {
    try {
        isItNull.Peek();
    }

    catch (NullPointerException e) {
        return false;
    }
    return true;
}

public static boolean openParenths(DoublyLinkedStack isItOpen) {

    if (toCheckForNull(isItOpen) == true) {

        if (isItOpen.Peek().equals("(") || isItOpen.Peek().equals("[") || isItOpen.Peek().equals("{")) {
            return true;

        } else {
            return false;
        }

    } else {
        return true;
    }
}

}

...