在链表集合中增加/删除元素 本题目已定义一个 People 类。属性:名字(name)、年龄(age);方法:getName() 获取名字、toString() 输出对象。 现使用链表存储 People 对象。首先,通过输入创建 People 对象并插入到链表;然后,删除指定名字的链表元素。
时间: 2023-12-10 16:37:19 浏览: 108
下面是一个使用链表存储 People 对象,并实现插入和删除指定名字元素的示例代码:
```java
import java.util.LinkedList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
LinkedList<People> list = new LinkedList<>();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入People的名字和年龄(用空格隔开),输入exit结束:");
String input = sc.nextLine();
if (input.equals("exit")) {
break;
}
String[] inputArr = input.split(" ");
String name = inputArr[0];
int age = Integer.parseInt(inputArr[1]);
People p = new People(name, age);
list.add(p);
}
System.out.println("插入后的链表元素:");
for (People p : list) {
System.out.println(p.toString());
}
System.out.println("请输入要删除的People的名字:");
String name = sc.nextLine();
boolean isRemoved = false;
for (People p : list) {
if (p.getName().equals(name)) {
list.remove(p);
isRemoved = true;
break;
}
}
if (isRemoved) {
System.out.println("删除成功!");
} else {
System.out.println("未找到该元素!");
}
System.out.println("删除后的链表元素:");
for (People p : list) {
System.out.println(p.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 +
'}';
}
}
```
运行示例:
```
请输入People的名字和年龄(用空格隔开),输入exit结束:
Alice 18
请输入People的名字和年龄(用空格隔开),输入exit结束:
Bob 20
请输入People的名字和年龄(用空格隔开),输入exit结束:
Cathy 22
请输入People的名字和年龄(用空格隔开),输入exit结束:
exit
插入后的链表元素:
People{name='Alice', age=18}
People{name='Bob', age=20}
People{name='Cathy', age=22}
请输入要删除的People的名字:
Bob
删除成功!
删除后的链表元素:
People{name='Alice', age=18}
People{name='Cathy', age=22}
```
阅读全文