使用链表进行堆栈,使用后缀表达式读取输入文件

时间:2018-04-27 01:45:33

标签: java linked-list stack

我需要使用链表填充堆栈。我有一个名为GenericStack的泛型类,它有常规方法。我有一个Evaluator类,它有我的main方法,我必须读取后缀表达式的输入文件。我有一个Node类来构建链表。要使用后缀表达式(如6 5 2 3 + 8 * + 3 + *)读取文件,我不知道如何使用文件填充链接列表或如何阅读它。

 public class GenericStack {
        private Node top;
        public GenericStack(){
            top = null;
        }

        public boolean isEmpty(){
            return (top == null);
        }

        public void push (Object newItem){
            top = new Node(newItem,top);
        }

        public Objectpop(){
            if(isEmpty()){
                System.out.println("Trying to pop when stack is empty.");
                return null;
            }
            else{
                Node temp = top;
                top = top.next;
                return temp.info;
            }
        }

        void popAll(){
            top = null;
        }

        public Object peek(){
            if(isEmpty()){
                System.out.println("Trying to peek when stack is empty.");
                return null;
            }
            else{
                return top.info;
            }
        }
    }

    public class Evaluator {
        public static void main(String[] args){
            GenericStack myStack = new GenericStack();
        }
    }


public class Node {
    Object info;
    Node next;

    Node(Object info, Node next){
        this.info = info;
        this.next = next;
    }

}

1 个答案:

答案 0 :(得分:0)

使用java.util.Scanner逐行读取文件。然后自己实施evaluation()方法

import java.io.File;
import java.io.IOException;
import java.util.*;

public class Evaluator {

// Method that evaluates postfix expressions
private static int evaluate(String expression) {

    Stack<Character> stack = new Stack<>();

    // Implement evaluation algorithm here

    return 0;
}

public static void main(String[] args) throws IOException {

    // Path to file
    String path = "file.txt";

    // Reference to file
    File file = new File(path);

    // Scanner that scans the file
    Scanner scanner = new Scanner(file);

    // List that will contain lines from file
    List<String> list = new ArrayList<>();

    // Read file in memory, line by line
    while (scanner.hasNextLine()) {

        // Add each line to list
        list.add(scanner.nextLine());
    }

    int result;

    // Loop through each line in list
    for (String line : list) {

        // Evaluate postfix expression
        result = evaluate(line);

        // Display expression = result
        System.out.println(line + " " + result);
    }

}

}