如何从含Integer链表属性的对象中按列提取数字存入队列
按列提取多个LinkedList元素的实现思路
你的需求本质是将多个LinkedList按列优先的方式合并到队列中,而非逐个链表拼接。针对链表长度不确定的问题,推荐两种高效实现思路:
方法一:使用迭代器跟踪遍历位置(推荐)
利用Iterator逐个跟踪每个链表的当前遍历位置,无需提前知道链表长度,也不会出现索引越界问题,且效率更高(尤其针对长链表)。
代码示例
// 假设你的Process对象集合 ArrayList<MyClassName> processList = ...; Queue<Integer> processQueue = new LinkedList<>(); // 收集所有链表的迭代器 List<Iterator<Integer>> iterators = new ArrayList<>(); for (MyClassName process : processList) { iterators.add(process.getLinkedList().iterator()); } boolean hasRemainingElements = true; while (hasRemainingElements) { hasRemainingElements = false; // 逐列遍历:每次取每个链表的下一个元素(如果存在) for (Iterator<Integer> iterator : iterators) { if (iterator.hasNext()) { processQueue.add(iterator.next()); hasRemainingElements = true; // 只要有元素未处理,继续循环 } } }
原理说明
- 先为每个LinkedList创建迭代器,保存到列表中;
- 循环遍历迭代器列表,每次取出当前迭代器的下一个元素(如果存在);
- 只有当所有迭代器都没有剩余元素时,才终止循环。
方法二:基于最大长度的索引遍历
如果链表长度普遍较短,可以先计算所有链表的最大长度,再按索引逐列提取元素。
代码示例
ArrayList<MyClassName> processList = ...; Queue<Integer> processQueue = new LinkedList<>(); // 先找到最长链表的长度 int maxLength = 0; for (MyClassName process : processList) { int currentLen = process.getLinkedList().size(); if (currentLen > maxLength) { maxLength = currentLen; } } // 按索引遍历每一列 for (int index = 0; index < maxLength; index++) { for (MyClassName process : processList) { LinkedList<Integer> list = process.getLinkedList(); if (index < list.size()) { // 避免索引越界 processQueue.add(list.get(index)); } } }
注意事项
LinkedList的get(index)方法是O(n)时间复杂度,因为需要从头遍历到目标索引位置,所以长链表场景下不推荐此方法,会导致性能下降。
两种方法对比
| 方法 | 优势 | 适用场景 |
|---|---|---|
| 迭代器法 | 无需提前计算长度、无索引越界风险、效率高 | 所有场景,尤其长链表 |
| 索引遍历法 | 逻辑直观 | 短链表场景 |
内容的提问来源于stack exchange,提问作者javaloaf
相关产品推荐
相关产品推荐

