为什么链接列表上的这种合并排序不正常?

时间:2017-04-21 13:18:29

标签: java linked-list mergesort

(免责声明:对于学校,因此无法导入其他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”,因为我创建了一个主函数并使用它来玩)

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:1)

关键点是方法sortTrack中的第二行:

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

我在我的笔记本电脑上测试过,现在一切顺利xD