我需要从文件读入整数到链表中,使用插入排序对列表进行排序,然后报告我的机器花费多长时间完成插入排序使用java。目前,我的代码除了从文件中读取外,其它都正确,它只读取第一个和最后一个数字。例如,如果我从相反顺序的数字1到5000的文件读取,它只会读取和排序5000和1。将从文件读取的整数插入到链接列表中java
如何将文件中的所有整数读入ListNodes?代码贴在下面:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class InsertionLinkedList {
public static ListNode insertionSortList(ListNode head) {
long start = System.nanoTime();
if (head == null || head.next == null)
return head;
ListNode newHead = new ListNode(head.val);
ListNode pointer = head.next;
// loop through each element in the list
while (pointer != null) {
// insert this element to the new list
ListNode innerPointer = newHead;
ListNode next = pointer.next;
if (pointer.val <= newHead.val) {
ListNode oldHead = newHead;
newHead = pointer;
newHead.next = oldHead;
} else {
while (innerPointer.next != null) {
if (pointer.val > innerPointer.val && pointer.val <= innerPointer.next.val) {
ListNode oldNext = innerPointer.next;
innerPointer.next = pointer;
pointer.next = oldNext;
}
innerPointer = innerPointer.next;
}
if (innerPointer.next == null && pointer.val > innerPointer.val) {
innerPointer.next = pointer;
pointer.next = null;
}
}
// finally
pointer = next;
}
long time = System.nanoTime() - start;
System.out.printf("The time taken was %.1f ns%n", (double) time);
return newHead;
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("random5k.txt"));
ListNode insertion = new ListNode(scanner.nextInt());
while(scanner.hasNextInt()){
ListNode nextNode = new ListNode(scanner.nextInt());
insertion.next = nextNode;
}
insertion = insertionSortList(insertion);
}
}
欢迎来到Stack Overflow!看起来你可能会问作业帮助。虽然我们本身没有任何问题,但请观察这些[应做和不应该](http://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions/338845#338845),并相应地编辑您的问题。 (即使这不是家庭作业,请考虑建议。) –
我解决了我的问题以匹配那些dos和dont的。 –
不过,这看起来像你需要学习使用调试器。请帮助一些[互补调试技术](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。如果您之后仍然遇到问题,请随时回答一个更具体的问题。 –