我正在尝试制作一个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

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

10-07 19:07
查看更多