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);
}
}
# 1 楼答案
据我所知,您需要使用Set功能从LinkedList中删除重复项,并使用SortedSet对其进行排序
所以,如果你有一个链表,最简单的方法就是这样做。在本例中,我使用了LinkedList,其中将填充随机数:
我们还可以重构:
# 2 楼答案
因为这显然是一个家庭作业(或类似的学习练习),所以给你代码是不合适的。因此,这里有一些提示可以帮助您开始
您需要始终保持链表元素的有序性
如果链表是一个包装的
LinkedList
,那么可以将许多SortedSet
方法委托给链表可选地,考虑使用^ {CD3>}作为集合的基类。
(你需要检查作业要求的措辞,以确定你是否被允许使用
LinkedList
或AbstractList
。)