在我正在进行的编码练习中,我试图生成 25 个随机整数,并使用对它们进行排序的函数将它们插入到链表中。我了解如何分别完成这些任务,但我想尝试将它们作为流来完成。这是我编写的代码,用于使用示例列表进行设置,以确保 insertSorted 函数有效。
节点.java
class Node<T extends Comparable<T>> {
T data;
Node<T> nextNode;
Node(T data) {
this(data, null);
};
Node(T data, Node<T> nextNode){
this.data = data;
this.nextNode = nextNode;
};
void setNext(Node<T> next){
nextNode = next;
}
}
排序列表.java
import java.util.NoSuchElementException;
class SortedList<T extends Comparable<T>> {
private Node<T> firstNode;
private Node<T> lastNode;
private String name;
SortedList(String listName){
name = listName;
firstNode = lastNode = null;
}
void insertSorted(T item){
if(isEmpty()){
lastNode = new Node<T>(item);
firstNode = lastNode;
} else if(firstNode.data.compareTo(item) > 0){
firstNode = new Node<T>(item, firstNode);
}
else {
Node<T> compareNode = firstNode;
while(compareNode.nextNode != null
&& compareNode.nextNode.data.compareTo(item) < 0){
compareNode = compareNode.nextNode;
}
Node<T> itemNode = new Node<T>(item, compareNode.nextNode);
compareNode.setNext(itemNode);
}
}
private boolean isEmpty() { return firstNode == null; }
void print() {
if (isEmpty()){
System.out.printf("Empty %s%n", name);
return;
}
System.out.printf("%s is: ", name);
Node<T> current = firstNode;
while (current != null){
System.out.printf("%s ", current.data);
current = current.nextNode;
}
System.out.println();
}
}
主.java
class Main{
public static void main(String[] args){
// sample example
SortedList<Integer> sample = new SortedList<>("sample list");
sample.insertSorted(84);
sample.insertSorted(65);
sample.insertSorted(134);
sample.insertSorted(102);
sample.insertSorted(954);
sample.insertSorted(755);
sample.print();
}
}
我知道我可以使用如下代码从流中生成一个随机整数数组:
int[] arr = new SecureRandom().ints(25, 0, 100).toArray();
如何使用 insertSorted 方法在上面的 SortedList 对象中包含随机 int 流?