I have two classes:
public class List {
public Node _head;
}
And:
public class Node {
public String _word;
public Node _next;
}
I have a constructor in "List", which gets a String as a parameter and puts every word in a seperate Node, like this:
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;
}
}
}
Anyway, when I'm trying to use a mergesort on the linked list, I can't manage to get it working.
This is the sorting code:
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;
}
Any idea what's wrong? I'm trying to make a new TextList with the String "Hello New World A Dawn Is There" and Output is: "There World"..
Please change as below. I think you forgot to assign the
curr
node to the appropriate values after theif-else
.