我需要從文件讀入整數到鏈表中,使用插入排序對列表進行排序,然後報告我的機器花費多長時間完成插入排序使用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/)。如果您之後仍然遇到問題,請隨時回答一個更具體的問題。 –