Hey guys, i need to construct text to a linked list and then sort it lexicographically, i used merge sort method for that,
but it triggers stack overflow when going to my split method , and i can't seem to find what's wrong with the recursion.
ideas?
public class TextList { WordNode _head; public TextList () { _head = null; } public TextList (String text) { construct(text); mergeSort(_head); } private WordNode construct(String text) { int i = 0; String tmp = ""; int index = 0; if (text != null) { for (; i < text.length() ; i++ ) { if (text.charAt(i) == ' ') { index++; _head = new WordNode(tmp); _head.setNext(addText(_head, text.substring(index))); return _head; } else // charAt i = a characeter { tmp += text.charAt(i); index++; } } } _head = null; return _head; } private WordNode addText(WordNode behind, String text) { String tmp = ""; int index = 0; while (index < text.length()) { if (text.charAt(index) == ' ') { WordNode tmpo = new WordNode(tmp); behind.setNext(tmpo); index++; behind = tmpo; tmp = ""; } else // charAt i = a characeter { tmp += text.charAt(index); index++; } } WordNode tmpo = new WordNode(tmp); behind.setNext(tmpo); return _head; } private WordNode mergeSort (WordNode node) { if (node == null || node.getNext() == null) return null; WordNode list2 = split(node); node = mergeSort(node); list2 = mergeSort(list2); return merge(node, list2); } private WordNode split(WordNode node) { if (node == null || node.getNext() == null) return null; WordNode list2 = node.getNext(); node.setNext(list2.getNext()); list2.setNext(split(list2.getNext())); <<<<----------- Stack overFlow happens in here return list2; } private WordNode merge(WordNode list1, WordNode list2) { if(list1 == null) return list2; if(list2 == null) return list1; if (list1.getValue().compareTo(list2.getValue()) < 0) { list1.setNext(merge (list1.getNext(), list2)); return list1; } else { list2.setNext(merge(list1, list2.getNext())); return list2; } } public String toString() { WordNode temp = _head; if (temp == null) return ""; return toString(temp, 1, temp.getValue(), ""); } private String toString(WordNode node, int count, String current, String res) { if (node == null) return res; if (node.getNext() == null) { current = node.getValue(); res += current + "\t" + count + "\n"; return res; } if (node.getValue() == node.getNext().getValue()) { count++; return toString(node.getNext(), count, current, res); } else { current = node.getValue(); res += current + "\t" + count + "\n"; return toString(node.getNext(), 1, current, res); } } }
this is my tester :
public class Tester { public static void main(String args[]) { TextList List0 = new TextList(); System.out.println(List0); TextList List1 = new TextList("hello nice to meet you my name is "); System.out.println(List1); } }
I spared you some other code that i wrote that i think that is irrelevant, and there is another class called WordNode to store data of the node
with getters and setters and somemore.
Thanks!