0

我使用 LinkedList 作为动态数组,然后该数组包含需要使用合并排序算法按字母顺序排序的字符串,该算法被添加到方法中,但结果无法正常工作。有什么建议么?

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;
    }
4

1 回答 1

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
        }
于 2013-05-19T14:08:43.993 回答