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