为什么链表上的合并排序不能正常工作?

Why isnt this merge sort on linked list working properly?

(免责声明:用于学校,因此无法导入其他 Java 实用程序)

所以我要对一个链表进行归并排序,我也差不多都下来了。这是:

class musicNode {
String track;  // The name of the track
int played= 0; // The number of times played
int shuffleTag= 0; // For shuffling
musicNode next;

public musicNode() {        // Here's how we construct an empty list.
    next = null;
}
public musicNode(String t) {
    track = t; next = null;
}
public musicNode(String t, musicNode ptr) {
    track = t; next = ptr;
}

public boolean LTTrack(musicNode x) {   // Compares tracks according to alphabetical order on strings
    if (this.track.compareTo(x.track)<=0) return true;
    else return false;
}
}; 

// This class represents a playlist;
// We assume that each track appears at most once in the playlist

public class MusicPlayer {
protected musicNode head = null; // Pointer to the top of the list.
int length=0;   // the number of nodes in the list.
boolean debug= false;

public  MusicPlayer() {
}
public void setToNull() {
    head = null;
}
public boolean isEmpty() {
    return head == null;
}

public musicNode head() {
    return head;
}

void insertTrack(String name) { // Inserts a new track at the top of the list.
    musicNode temp= new musicNode(name, head);
    head= temp;
    length++;
}

void sortTrack() { // TODO
    musicNode main = this.head;
    mergeSort(main);
}


public musicNode mergeSort(musicNode head) {
    if ((head == null) || (head.next == null)){
        return head;
    }
    musicNode left = head;
    musicNode right = head.next;

    while((right != null) && (right.next != null)){
        head = head.next;
        right = (right.next).next;
    }
    right = head.next;
    head.next = null;

    return merge(mergeSort(left), mergeSort(right));
}

还有这个 JUnit 测试:

public void testSortMixed() {   
    MusicPlayer trackList= new MusicPlayer();
    trackList.insertTrack("d");
    trackList.insertTrack("b");
    trackList.insertTrack("e");
    trackList.insertTrack("a");
    trackList.insertTrack("c");

    MusicPlayer trackListTwo= new MusicPlayer();
    trackListTwo.insertTrack("e");
    trackListTwo.insertTrack("d");
    trackListTwo.insertTrack("c");
    trackListTwo.insertTrack("b");
    trackListTwo.insertTrack("a");

    trackList.sortTrack();
    musicNode tmp= trackList.head;
    musicNode tmp2= trackListTwo.head;
    for(int i=0; i< 5; i++){
        assertEquals(tmp2.track, tmp.track);
        tmp2= tmp2.next;
        tmp=tmp.next;
    }
}

问题是它会根据您插入的最后一首曲目进行排序,并且只能从那时起进行排序。所以假设你从 a-f 插入字母,但你插入的最后一个是 "c",它只会显示你 "cdef"。但如果最后一个是 "a" 那么它会按预期工作。

它的工作原理是,当您插入曲目时,它会插入到列表的开头,而不是结尾,成为开头。我觉得这可能是什么搞砸了,因为我根据我的笔记和插入在底部的在线内容进行了调整和查看。

虽然我不知道如何解释这一点。我也知道它根据最后插入的内容进行排序(在上面的 JUnit 测试中它排序为 "cde" 因为我创建了一个 main 函数并使用它)

感谢任何帮助。

重点是方法sortTrack中的第二行:

void sortTrack() {
    musicNode main = this.head;
    this.head = mergeSort(main); // you forgot to set the head of linked list to the merged
}

我已经在笔记本电脑上测试过了,现在一切正常 xD