【发布时间】:2016-03-11 00:51:32
【问题描述】:
我正在尝试使用 LinkedList 实现合并排序,到目前为止,
class Node{
Node next;
int data;
public Node (){
}
public Node(int _data){
this.data = _data;
}
}
public class myTest{
private static Node head;
private static Node current;
public void myTest(){
this.head = null;
this.current = null;
}
public static void insert( int data ){
Node newNode = new Node(data);
if (head == null){
head = newNode;
current = head;
}
else {
current.next = newNode;
current = newNode;
}
}
public static void display(Node cur ){
while( cur != null){
if (cur.next != null){
System.out.print(cur.data + " -> ");
}
else{
System.out.print(cur.data +" ");
}
cur = cur.next;
}
System.out.println();
}
private static Node mergeSort(Node headOriginal ){
if (headOriginal == null || headOriginal.next == null ){
return headOriginal;
}
Node a = headOriginal;
Node b = headOriginal.next;
while( b != null && b.next != null ){
headOriginal = headOriginal.next;
b = (b.next).next;
}
// split in 2 parts
b = headOriginal.next;
headOriginal.next = null;
return merge( mergeSort(a), mergeSort(b) );
}
// sort among the 2 parts
public static Node merge(Node a, Node b) {
Node c = new Node();
Node head_1 = c;
while ((a != null) && (b != null)) {
if ( a.data <= b.data ){
c.next = a;
c = a;
a = a.next;
}
else {
c.next = b;
c = b;
b = b.next;
}
}
c.next = (a == null) ? b : a;
return head_1.next;
}
public static void main(String[] args ){
int [] arr = {12, 34, 5, 6, 7};
for (int j =0; j < arr.length; j++){
insert( arr[j] );
}
mergeSort(head);
display(head);
}
}
mergeSort 函数采用由 insert 函数生成的 LikedList 的原始头部。我相信该函数正确地创建了一个升序排序的 LL。 display 函数假设打印 LL。在这种情况下,它仅从原始头 (12) 打印到排序的 LL 的末尾并打印 '12->34' 。我假设如果我可以通过新创建的排序 LL 的头部,它将能够打印整个排序的 LL。
- 我的程序是否正常或需要一些改进来实现归并排序?
- 如何让排序的 LL 的头部通过 display 方法?
【问题讨论】:
-
链表是一个非常错误的数据结构,我相信使用合并排序。
-
我喜欢解决不同的编程问题,这更多是为了学习和从中获得乐趣。