将文本从txt文件放入链接列表

时间:2014-02-22 20:26:08

标签: java linked-list stringtokenizer

我正在尝试将数值表达式行标记为CS项目的链接列表。我必须使用我在之前实验室中创建的链接列表。

我对一行的每个数字和运算符进行标记,并将每个标记插入到链接列表中的节点中,因为它们是标记化的。当我编写程序以在标记化时打印出每个标记时,将打印每个标记。但是当我告诉它打印出包含每个标记作为节点的链表时,一些运算符丢失了。我不知道这种行为的原因是什么。

以下是创建包含每个标记的链接列表的方法:

    public static LinkedListTest ReadInFile(String path){
    File file = new File(path);
    LinkedListTest list = new LinkedListTest();

    try {
        Scanner scanner = new Scanner(file);
        int count = 0;

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            StringTokenizer st = new StringTokenizer(line);
            while (st.hasMoreTokens()){
                list.insert(st.nextToken());
            }
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return list;
}

以下是插入链接列表并打印链接列表的方法:

public class LinkedListTest implements LinkedList {
private Node head;

public LinkedListTest(){
    head = new Node();
}

public void insert(Object x){
    if (lookup(x) == false){

        if (head.data == null)
            head.data = x;

        else{
        /*
        Node NewNode = new Node();
        NewNode.data = x;
        NewNode.next = head;
        head = NewNode;
        */

            //InsertLast
            Node temp = head;

            while (temp.next != null){
                temp = temp.next;
            }

            Node NewNode = new Node();
            NewNode.data = x;
            NewNode.next = null;

            temp.next = NewNode;

        }
    }
}

public void printList(){
    Node temp = head;

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

    System.out.print(temp.data + " ");
}
}

1 个答案:

答案 0 :(得分:0)

我解决了。我的插入函数上的lookup子句搞砸了。