原题链接:[编程入门]链表之节点删除
解题思路:
遍历链表a,对于a中的每一个元素,判断链表b中是否包含这个元素,是,a删去这个元素。
注意事项:
1.创建一个类Stu,对equals方法进行重写,逻辑为当两个Stu的id相等即返回真,为什么要重写这个equals方法?——在代码中会使用到ArrayList的contains方法,这个方法会调用容器元素的equals方法判断两个元素是否相同,相关的知识点可以查阅相关资料。
2.在使用for-each迭代时,在for-each内部删除元素直接调用ArrayList的remove方法会抛出并发修改异常,这里使用迭代器进行删除。
参考代码:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n,m;
n=scanner.nextInt();
m=scanner.nextInt();
List<Stu> a=new ArrayList<Stu>();
List<Stu> b=new ArrayList<Stu>();
for(int i=0;i<n;i++){
int id=scanner.nextInt();
int score=scanner.nextInt();
a.add(new Stu(id,score));
}
for(int i=0;i<m;i++){
int id=scanner.nextInt();
int score=scanner.nextInt();
b.add(new Stu(id,score));
}
//在a链表中找出b链表有相同学号的点并去除
Iterator<Stu> iterator = a.iterator();
while (iterator.hasNext()){
Stu next = iterator.next();
if(b.contains(next)){
iterator.remove();
}
}
System.out.println(a.size());
for(Stu stu:a){
System.out.println(stu.id+" "+stu.score);
}
}
static class Stu{
int id;
int score;
Stu(int i,int s){
this.id=i;
this.score=s;
}
@Override
public boolean equals(Object o) {
Stu stu = (Stu) o;
return this.id==stu.id;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + score;
return result;
}
}
}0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复