对链接的字符串列表进行排序

时间:2018-03-23 11:01:23

标签: java sorting linked-list bubble-sort

public class LinkedList {
    private Node top;

    public LinkedList() {
        top = null;
    }

    public void add(String data) {
        Node temp = new Node(data, top);
        top = temp;
    }

    public void sort() {
        LinkedList sortedList = new LinkedList();
        Node i;
        Node j;
        String temp;
        String temp2;
        String temp3;
        for (i = top; i != null; i.getNext()) {
            for (j = i.getNext(); j != null; j.getNext()) {
                if (i.getData().compareTo(j.getData()) < 0) {
                    temp = i.getData();
                    i.setData(temp);
                    temp2 = j.getData();
                    j.setData(temp2);
                    temp3 = temp;
                    temp = temp2;
                    temp2 = temp3;
                    sortedList.add(temp3);
                } else if (i.getData().compareTo(j.getData()) > 0) {
                    temp3 = i.getData();
                    sortedList.add(temp3);
                }
            }
        }
    }
}

有人可以查看我的代码并告诉我为什么我的temptemp2永远不会被分配和使用?为什么这不起作用?

当我运行main时,我只得到原始的链表而不是已排序的链表。

我的逻辑是否正确?我试图按升序对字符串进行排序。

2 个答案:

答案 0 :(得分:0)

由于OP更新了他的代码片段,以下代码无法工作,因为提到的LinkedList是自定义List而不是java.util.LinkedList。

由于缺少“top”变量,无法运行代码。 顺便说一句,如果您需要将i和j的所有值都放到单个且已排序的LinkedList中,请尝试以下方法:

no-argument

答案 1 :(得分:0)

说明

您正在将(可能的)已排序值分配给新列表sortedList。此列表与您的原始列表(this)有。因此,您的原始列表不会发生变化。

最后,您需要将sortedList的结构复制到当前实例,或直接就地排序。

解决方案

因此,假设您的排序确实有效,请将此类内容附加到sort()的末尾:

// Copy data of sorted list over to own instance
Node currentSortedElement = sortedList.top;
Node currentNonSortedElement = top;

while (currentSortedElement != null) {
    // Extract data and copy over
    currentNonSortedElement.setData(currentSortedElement.getData());

    // Prepare next iteration
    currentSortedElement = currentSortedElement.next;
    currentNonSortedElement = currentNonSortedElement.next;
}

因此请查看以下列表

index      | 0  1  2  3  4  5
-----------|-----------------
sorted     | 1  4  4  6  8  9
non-sorted | 4  1  6  9  8  4

该算法只会将排序列表中每个项目的数据复制到同一索引处的非排序列表中的项目,所以

index      | 0  1  2  3  4  5
-----------|-----------------
sorted     | 1  4  4  6  8  9
           | |  |  |  |  |  |
           | v  v  v  v  v  v
non-sorted | 1  4  4  6  8  9

备注

根据您的评论,您尝试实施Bubblesort。请考虑查看相关问题Bubble Sort Manually a Linked List in Java,其中显示了一个有效的代码示例,并附有说明。