我正在尝试创建一个能够从内容添加为数据文件的 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++;
}
对于排序,链表的自下而上的合并排序相当快。维基文章包括伪代码示例:
https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation_using_lists
根据节点的大小,从列表创建数组,对数组进行排序,然后从排序的数组创建新的排序列表可能会更快。