基于链表的有序集

时间:2016-06-04 22:49:36

标签: java sortedset

我正在使用java,我需要使用SortedSet接口在链表上实现一个有序集。如何通过这种条件从SortedSet实现方法?

2 个答案:

答案 0 :(得分:1)

由于这显然是家庭作业(或类似的学习练习),因此给你代码是不合适的。所以这里有一些提示来帮助您入门。

  1. 您需要始终保持链接列表的元素

  2. 如果链接列表是包装LinkedList,您可以将许多SortedSet方法委派给列表。

  3. 或者,考虑使用AbstractSet作为您的集合的基类。

  4. (您需要检查作业的措辞,以确定您是否允许使用LinkedListAbstractList

答案 1 :(得分:0)

据我了解,您需要使用Set功能从LinkedList中删除重复项,并使用SortedSet对其进行排序。

因此,如果您有链接列表,最简单的方法是执行此类操作。对于这个例子,我使用了LinkedList,它将填充随机数:

public class Main {
public static void main(String[] args){
    //Declare the LinkedList of Integers
    LinkedList<Integer> linkedList = new LinkedList<Integer>();
    //use special method to fill List with 10 numbers which are less than 100
    linkedListRandomFill(linkedList, 10, 100);

    //After you pass the LinkedList to the following constructor
    //  the list is sorted automatically
    SortedSet<Integer> sortedSet = new TreeSet<Integer>(linkedList);

    //After that you can recreate your linked list,
    //  just pass the SortedSet to LinkedList constructor
    linkedList = new LinkedList<Integer>(sortedSet);
    System.out.println(linkedList);
}

public static void linkedListRandomFill(
        LinkedList<Integer> linkedList,
        int size,
        int limit){
    Random rnd = new Random();
    for(int i = 0; i < size; i++){
        linkedList.add(rnd.nextInt(limit));
    }
}

我们也可以重构:

public class Main {
    public static void main(String[] args){
        LinkedList<Integer> linkedList = new LinkedList<Integer>();
        linkedListRandomFill(linkedList, 10, 100);
        linkedList = getSortedListOfUniqueValues(linkedList);
        System.out.println(linkedList);
    }

    public static void linkedListRandomFill(
            LinkedList<Integer> linkedList,
            int size,
            int limit){
        Random rnd = new Random();
        for(int i = 0; i < size; i++){
            linkedList.add(rnd.nextInt(limit));
        }
    }

    public static LinkedList<Integer> getSortedListOfUniqueValues(LinkedList<Integer> list){
        SortedSet<Integer> sortedSet = new TreeSet<Integer>(list);
        return new LinkedList<Integer>(sortedSet);
    }
}
相关问题