【问题标题】:How can I read from a file and alphabetically order the contents of that file into a Linked List?如何从文件中读取并将该文件的内容按字母顺序排列到链接列表中?
【发布时间】:2020-02-18 00:32:50
【问题描述】:

我正在尝试创建一个 LinkedList 类,该类能够从内容中添加为数据文件。我被抛出一个 NullPointerException,我不完全确定为什么。有没有更好的方法来解决这个问题而不使用 Collections.sort?

public class LinkedList {

    // Properties
    Node head;
    int count;

    // Constructors
    public LinkedList() {
        head = null;
        count = 0;
    }

    public LinkedList(Node newHead) {
        head = newHead;
        count += 1;
    }

    // Methods
    // add
    public void add(String newData) {
        Node temp = new Node(newData);
        Node current = head;

        while (current.getNext() != null) {
            current = current.getNext();
        }
        current.setNext(temp);
        count++;
    }

//================================================================================================

    public static void main(String[] args) throws IOException {
        // Access the contents of a file
        File file = new File("C:\\Users\\Marlene\\Workspace\\LinkedDict\\src\\com\\company\\unsorteddict.txt");
        Scanner scan = new Scanner(file);

        String fileContents = "";
        LinkedList linkedList = new LinkedList();

        com.company.LinkedList linkedList = new com.company.LinkedList();
        while (scan.hasNextLine()) {
            linkedList.add(fileContents);
        }

        FileWriter writer = new FileWriter(
                "C:\\Users\\Marlene\\Workspace\\LinkedDict\\src\\com\\company\\sorteddict.txt");
        writer.write(fileContents);
        writer.close();
    }
}

【问题讨论】:

  • 欢迎来到 StackOverflow。请按照您创建此帐户时的建议阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确说明问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您指定的问题。特别是,包括完整的错误消息(回溯)和您对关键值的跟踪。

标签: java sorting linked-list nullpointerexception


【解决方案1】:

评论中注明的修复。

    public void add(String newData) {
        Node temp = new Node(newData);
        if(head == null){                    // fix
            head = temp;
            count = 1;
            return;
        }
        Node current = head;
        while (current.getNext() != null) {
            current = current.getNext();
        }
        current.setNext(temp);
        count++;
    }

对于排序,链表的自下而上合并排序相当快。 Wiki 文章包含伪代码示例:

https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation_using_lists

根据节点的大小,从列表中创建一个数组,对数组进行排序,然后从排序后的数组中创建一个新的排序列表,可能会更快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2021-06-29
    • 2014-08-15
    相关资源
    最近更新 更多