【发布时间】:2015-06-21 20:26:37
【问题描述】:
我有两个班级:
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;
}
知道有什么问题吗? 我正在尝试使用字符串“Hello New World A Dawn Is There”创建一个新的 TextList,输出为:“There World”..
【问题讨论】:
-
为什么要重新发明链表和排序?你不能只用
java.util.LinkedList和java.util.Collections.sort吗? -
@kosmaty 我认为他正在学习实现 LinkedList。您是否尝试在排序之前打印数据?只是为了检查您的所有内容是否确实存在于 LinkedList 中
-
我正在尝试学习界面。我做到了,结果很好(只是颠倒了)。在我尝试排序之后,输出只是一团糟。
标签: java linked-list nodes mergesort