使用链接列表合并在字符串中排序

时间:2013-05-19 14:02:38

标签: arrays string linked-list mergesort compareto

我使用LinkedList作为dymanic数组,然后这个数组包含需要通过使用合并排序算法按字母顺序排序的字符串,该算法在方法中添加并且结果不起作用。有什么建议吗?

public static LinkedList<String> merge(LinkedList<String> linkedList, LinkedList<String> linkedList2) {
        LinkedList<String> result = new LinkedList<String>();
        if(linkedList.size() == 0)
            result.add(linkedList2.remove());
        else if (linkedList2.size() == 0)
            result.add(linkedList.remove());

        for(int i=0; i<linkedList.size(); i++) {
            if(linkedList.get(i).compareTo(linkedList2.get(i)) < 0)
                result = linkedList;
            else
                result = linkedList2;
        }

        return result;
    }

1 个答案:

答案 0 :(得分:1)

这里的逻辑是错误的,请参阅正确逻辑的评论:

    while(0 < linkedList.size() || 0 < linkedList2.size())
        if(0 == linkedList.size())        // if linkedList is empty
            result.add(linkedList.remove());        // should add head of linkedlist2 to result
        else if (0 == linkedList2.size())        // vice
            result.add(linkedList2.remove());       // versa
        else {
            linkedList.get(0).compareTo(linkedList2.get(0));      // else add the smaller of the two; you are just comparing, not adding the smaller
        }