创建一个LinkedList数组,想数组中插入10个随机数,遍历输出这10个数,然后在n号位置插入一个数,最后删除m号位置的数
时间: 2024-02-28 17:52:10 浏览: 26
好的,下面是代码实现:
```java
import java.util.LinkedList;
import java.util.Random;
public class Main {
public static void main(String[] args) {
// 创建LinkedList数组
LinkedList<Integer>[] lists = new LinkedList[10];
for (int i = 0; i < lists.length; i++) {
lists[i] = new LinkedList<>();
}
// 向数组中插入10个随机数
Random random = new Random();
for (LinkedList<Integer> list : lists) {
for (int i = 0; i < 10; i++) {
list.add(random.nextInt(100));
}
}
// 遍历输出10个数
for (LinkedList<Integer> list : lists) {
System.out.println(list);
}
// 在n号位置插入一个数
int n = 5; // 假设要在第5个链表中插入一个数
int insertNumber = 888; // 假设要插入的数是888
lists[n-1].add(2, insertNumber); // 在第5个链表的第3个位置插入888
// 删除m号位置的数
int m = 7; // 假设要删除第7个链表的第4个数
lists[m-1].remove(3); // 删除第7个链表的第4个数
// 输出修改后的链表数组
System.out.println("修改后的链表数组:");
for (LinkedList<Integer> list : lists) {
System.out.println(list);
}
}
}
```
在上面的代码中,我们首先创建了一个长度为10的LinkedList数组,然后使用两个for循环向数组中的每个链表插入10个随机数。接着,我们使用for循环遍历输出了数组中的10个链表。
接下来,我们假设要在第5个链表中插入一个数,使用add方法在该链表的第3个位置插入了888。同时,我们也假设要删除第7个链表的第4个数,使用remove方法删除了该数。
最后,我们再次使用for循环遍历输出修改后的链表数组,以便验证我们的操作是否正确。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)