在链表集合中增加/删除元素 本题目已定义一个 People 类。属性:名字(name)、年龄(age);方法:getName() 获取名字、toString() 输出对象。 现使用链表存储 People 对象。首先,通过输入创建 People 对象并插入到链表;然后,删除指定名字的链表元素。
时间: 2023-12-10 20:37:31 浏览: 29
这里是一个示例代码,实现了链表集合中增加/删除元素的功能:
```java
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
LinkedList<People> list = new LinkedList<>();
Scanner scanner = new Scanner(System.in);
// 创建 People 对象并插入链表
System.out.println("请输入 People 对象的个数:");
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
System.out.println("请输入第 " + (i + 1) + " 个 People 对象的名字和年龄:");
String name = scanner.next();
int age = scanner.nextInt();
People p = new People(name, age);
list.add(p);
}
// 输出链表
System.out.println("插入后的链表为:");
System.out.println(list);
// 删除指定名字的链表元素
System.out.println("请输入要删除的 People 对象的名字:");
String name = scanner.next();
for (People p : list) {
if (p.getName().equals(name)) {
list.remove(p);
break;
}
}
// 输出链表
System.out.println("删除后的链表为:");
System.out.println(list);
}
}
class People {
private String name;
private int age;
public People(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
这个例子中,使用了 `LinkedList` 类来存储 `People` 对象。首先通过输入创建 `People` 对象,并插入到链表中。然后,输入要删除的 `People` 对象的名字,遍历链表并删除指定名字的元素。最后输出删除后的链表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)