所以我一直在尝试使用合并排序对链表进行排序,我找到了这段代码并尝试处理它,但它并没有真正起作用?
它可能有什么问题?我不太确定 getMiddle 方法,尽管我知道它应该获取列表的中间值以便处理列表本身的 2 个列表
这是代码;
public Node mergeSort(Node head) {
if (head == null || head.link == null) {
return head;
}
Node middle = getMiddle(head);
Node sHalf = middle.link;
middle.link = null;
return merge(mergeSort(head), mergeSort(sHalf));
}
public Node merge(Node a, Node b) {
Node dummyHead;
Node current;
dummyHead = new Node();
current = dummyHead;
while (a != null && b != null) {
if ((int) a.getData() <= (int) b.getData()) {
current.link = a;
a.link = a;
}
else {
current.link = b;
b.link = a;
}
current = current.link;
}
current.link = (a == null) ? b : a;
return dummyHead;
}
public Node getMiddle(Node head) {
if (head == null) {
return head;
}
Node slow, fast;
slow = fast = head;
while (fast.link != null && fast.link.link != null) {
slow = slow.link;
fast = fast.link.link;
}
return slow;
}
在主要方法中:
Object data;
MyLinkedList list = new MyLinkedList(); //empty list.
for (int i = 0; i < 3; i++) { //filling the list
data = console.nextInt();
list.insertAtFront(data);
}
System.out.print("Print(1): ");
list.printList();
list.mergeSort(list.getHead());
System.out.print("List after sorting: ");
list.printList();