恕我直言,这个概念是错误的。您不需要在这里使用合并排序。尝试搜索 PriorityQueue 或实际上 BinaryHeap 以解决此任务。其次,链表上的合并排序不是一个好主意,因为它根本没有效率。我认为你应该完全修改你的解决方案。
注意。为方便起见,只需实现 YourLinkedList.getByIndex() 操作,添加大小属性以保存链表中的项目数,然后再创建一个linkedList 并执行自下而上的合并排序,就像使用简单数组一样。
结构:
public class Item {
private String word;
private Item next;
public Item(String word) {
this.word = word;
}
public Item getNext() {
return next;
}
public void setNext(Item next) {
this.next = next;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
}
链表:
public class LinkedList {
private int size = 0;
private Item first = null;
public void swapFragment(LinkedList list, int from, int to) {
if (from >= 0 && to < size) {
list.get(to-from).setNext(this.get(to+1));
if (from > 0) {
this.get(from-1).setNext(list.get(0));
} else {
this.first = list.get(0);
}
}
}
public void addItem(String word) {
if (first == null) {
first = new Item(word);
} else {
Item item = first;
while (item.getNext() != null) {
item = item.getNext();
}
item.setNext(new Item(word));
}
this.size++;
}
public Item get(int index) {
if (index >= size) {
return null;
} else {
Item item = first;
for(int i = 1; i <= index; i++) {
item = item.getNext();
}
return item;
}
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String toString() {
Item item = first;
String message = null;
if (item != null) {
message = item.getWord() + " ";
} else {
return null;
}
while (item.getNext() != null) {
item = item.getNext();
message = message + item.getWord() + " ";
}
return message;
}
}
合并排序:
public class ListMergeSort {
public void sort(LinkedList list, int lo, int hi) {
if (hi <= lo) {
return;
}
int mid = lo + (hi-lo)/2;
sort(list, lo, mid);
sort(list, mid+1, hi);
merge(list, lo, hi, mid);
}
private void merge(LinkedList list, int lo, int hi, int mid) {
int i = lo;
int j = mid+1;
LinkedList newList = new LinkedList();
for (int k = lo; k <= hi; k++) {
if (i > mid) {
newList.addItem(list.get(j).getWord());
j++;
} else if (j > hi) {
newList.addItem(list.get(i).getWord());
i++;
} else if (list.get(i).getWord().compareTo(list.get(j).getWord()) < 0) {
newList.addItem(list.get(i).getWord());
i++;
} else {
newList.addItem(list.get(j).getWord());
j++;
}
}
list.swapFragment(newList, lo, hi);
}
}
字符串测试类:
import org.junit.*;
public class MergeTest {
@Test
public void testWords() {
LinkedList list = new LinkedList();
list.addItem("word");
list.addItem("pipe");
list.addItem("trainer");
list.addItem("stark");
list.addItem("33");
list.addItem("dmitry");
ListMergeSort lms = new ListMergeSort();
lms.sort(list, 0, list.getSize()-1);
}
}
现在您只需要创建一个接收字符串作为参数的类,使用 String.split() 将其拆分,并将生成的单词添加到内部 LinkedList 数据结构中。然后用合并排序对它们进行排序,然后得到结果。