使用链接列表堆栈,读取带有后缀表达式的输入文件



我需要用链接列表填充堆栈。我有一个带有常规方法的通用类,名为GenericStack。我有一个具有主要方法的评估器类,我必须读取后缀表达式的输入文件。我有一个节点类来构建链接列表。要使用后缀表达式读取文件,例如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;
    }
}

使用 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);
    }
}

}

相关内容

最新更新