在链表集合中增加/删除元素 本题目已定义一个 People 类。属性:名字(name)、年龄(age);方法:getName() 获取名字、toString() 输出对象。 现使用链表存储 People 对象。首先,通过输入创建 People 对象并插入到链表;然后,删除指定名字的链表元素。
时间: 2023-12-10 10:37:14 浏览: 61
以下是一个示例代码,可以实现链表集合中增加/删除元素的功能:
```java
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
List<People> peopleList = new LinkedList<>();
Scanner scanner = new Scanner(System.in);
// 通过输入创建 People 对象并插入到链表
while (true) {
System.out.print("请输入人名:");
String name = scanner.next();
if (name.equals("exit")) {
break;
}
System.out.print("请输入年龄:");
int age = scanner.nextInt();
People people = new People(name, age);
peopleList.add(people);
}
// 输出链表中的元素
System.out.println("链表中的元素:");
for (People people : peopleList) {
System.out.println(people.toString());
}
// 删除指定名字的链表元素
System.out.print("请输入要删除的人名:");
String name = scanner.next();
for (People people : peopleList) {
if (people.getName().equals(name)) {
peopleList.remove(people);
System.out.println("删除成功!");
break;
}
}
// 输出删除元素后的链表
System.out.println("删除元素后的链表:");
for (People people : peopleList) {
System.out.println(people.toString());
}
}
}
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 +
'}';
}
}
```
示例运行结果:
```
请输入人名:Tom
请输入年龄:18
请输入人名:Jerry
请输入年龄:20
请输入人名:Mike
请输入年龄:25
请输入人名:exit
链表中的元素:
People{name='Tom', age=18}
People{name='Jerry', age=20}
People{name='Mike', age=25}
请输入要删除的人名:Jerry
删除成功!
删除元素后的链表:
People{name='Tom', age=18}
People{name='Mike', age=25}
```
阅读全文