java - 如何从文件中读取内容并按字母顺序将该文件的内容排序到链接列表中?

标签 java sorting linked-list nullpointerexception

我正在尝试创建一个能够从内容添加为数据文件的 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();
    }
}

最佳答案

修复评论中提到的问题。

    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

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

关于java - 如何从文件中读取内容并按字母顺序将该文件的内容排序到链接列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58494424/

相关文章:

java - 如何禁用 GXT 中 DualListField 的 'Add Selected' 按钮?

ruby - 对范围数组进行排序

python - 在 Python 中按元素总和对组合进行排序

c++ - 基数排序功能出现问题

data-structures - 高效实现不可变(双重)链表

java - 使用 SwingWorker 高效发布

java - 发送前查找电子邮件大小

java - 尝试为 postgresql 使用 jdbc 驱动程序,但它不起作用

mysql - 如何在 SQL 中按数字排序的 select 语句中创建列

c++ - 试图制作一个包含字符串 C++ 的链表