我有兩個類:歸併不給正確的輸出
public class List {
public Node _head;
}
和:
public class Node {
public String _word;
public Node _next;
}
我在「名單」的構造函數,它得到一個字符串作爲參數,並把每一個字一個單獨的節點,就像這樣:
public List(String text) {
if (text.length() == 0)
_head = null;
createList(text);
}
private void createList(String text) {
int lastIndex=0;
String temp;
for (int i=0;i<text.length();i++) {
if (text.charAt(i)==' '|| i==text.length()-1) {
if (i == 0) { // Space in the begining
lastIndex=1;
continue;
}
if (i == text.length()-1) { // If we reached to the last char of the string
if (text.charAt(i) == ' ') { // If it's a space, don't include it
temp = text.substring(lastIndex,i);
} else {
temp = text.substring(lastIndex,i+1);
}
} else {
temp = text.substring(lastIndex,i);
}
addToBegining(temp);
lastIndex=i+1;
}
}
}
無論如何,當我試圖使用一個合併的鏈表上,我不能設法得到它活像國王。
這是排序代碼:
public Node merge_sort(Node h) {
if (h == null || h._next == null) { return h; }
Node middle = getMiddle(h); //get the middle of the list
Node sHalf = middle._next; middle._next = null; //split the list into two halfs
return merge(merge_sort(h), merge_sort(sHalf)); //recurse on that
}
public Node merge(Node a, Node b) {
Node dummyHead, curr;
dummyHead = new Node();
curr = dummyHead;
while (a !=null && b!= null) {
if (a._word.compareTo(b._word) <= 0) {
curr._next = a;
a = a._next;
} else {
curr._next = b;
b = b._next;
}
curr = curr._next;
}
curr._next = (a == null) ? b : a;
return dummyHead._next;
}
public Node getMiddle(Node h) {
if (h == null) { return h; }
Node slow, fast;
slow = fast = h;
while (fast._next != null && fast._next._next != null) {
slow = slow._next;
fast = fast._next._next;
}
return slow;
}
任何想法有什麼不對? 我試圖做一個新的TextList與字符串「你好新世界有一個黎明」和輸出是:「有世界」..
爲什麼你重塑鏈表和排序?你不能只使用java.util.LinkedList和java.util.Collections.sort嗎? –
@kosmaty我認爲他正在學習實施LinkedList。您是否在排序前嘗試打印數據?只是爲了檢查你的所有內容是否真的存在於LinkedList – user3337714
我正試圖學習界面。我做了,它出現了很好(剛剛顛倒過來)。在我嘗試排序後,輸出只是搞砸了。 – Osh24