编码练习:流式实现随机整数的泛型链表排序插入
嘿,我明白你想把生成随机数、排序插入泛型链表这俩事儿用流式风格串起来——这想法挺棒的,既简洁又符合现代Java的编程习惯。我来帮你把这个实现捋清楚!
流式实现排序插入泛型链表的方案
首先先把你提到的Node类补全(看起来你写了一半,我帮你收尾):
class Node<T extends Comparable<T>> { T data; Node<T> nextNode; // 构造方法:只传入数据,默认next为null Node(T data) { this(data, null); } // 全参构造方法 Node(T data, Node<T> nextNode) { this.data = data; this.nextNode = nextNode; } }
接下来我们需要一个泛型的有序链表类,核心是你的insertSorted方法,同时我们可以给它加一个方便验证的打印方法:
class SortedLinkedList<T extends Comparable<T>> { private Node<T> head; // 排序插入核心方法 public void insertSorted(T data) { Node<T> newNode = new Node<>(data); // 空链表或者新元素比头结点小,直接插在头部 if (head == null || data.compareTo(head.data) <= 0) { newNode.nextNode = head; head = newNode; return; } // 找到插入位置的前一个结点 Node<T> current = head; while (current.nextNode != null && current.nextNode.data.compareTo(data) < 0) { current = current.nextNode; } // 插入新结点 newNode.nextNode = current.nextNode; current.nextNode = newNode; } // 打印链表,用于验证排序结果 public void printList() { Node<T> current = head; while (current != null) { System.out.print(current.data + " -> "); current = current.nextNode; } System.out.println("null"); } }
现在重点来了——流式生成随机数并插入。我们可以用Java 8+的Stream API来生成25个随机整数,然后通过forEach直接调用insertSorted,完美实现流式处理:
import java.util.Random; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { SortedLinkedList<Integer> sortedList = new SortedLinkedList<>(); Random random = new Random(); // 流式生成25个0-99的随机整数,逐个插入有序链表 IntStream.generate(() -> random.nextInt(100)) .limit(25) .boxed() // 把int转换成Integer,适配泛型要求 .forEach(sortedList::insertSorted); // 打印验证结果 System.out.println("排序后的链表:"); sortedList.printList(); } }
为什么这是流式实现?
- 随机数是按需生成的:不是一次性生成25个存在数组里,而是生成一个、处理一个(插入链表),再生成下一个
- 整个流程是链式调用:从生成到插入的逻辑串在一起,不需要中间变量存储所有随机数
- 符合函数式编程风格:用
forEach替代传统的for循环,代码更简洁易读
验证要点
运行这段代码后,你会看到打印出来的链表是从小到大有序的,这就说明你的insertSorted方法和流式处理逻辑都没问题。如果想调整随机数的范围,只需要修改random.nextInt(100)里的参数就行。
内容的提问来源于stack exchange,提问作者Jack J
相关产品推荐
相关产品推荐

