解题思路:
遍历链表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 人评分
不知道哪里错了浏览:1146 |
C语言程序设计教程(第三版)课后习题8.2 (Java代码)浏览:2269 |
奖学金 (C++代码)浏览:2008 |
C语言训练-列出最简真分数序列* (C语言代码)浏览:506 |
C二级辅导-进制转换 (C语言代码)浏览:615 |
字符串比较 (C语言代码)答案错误????浏览:597 |
WU-字符串比较 (C++代码)浏览:760 |
C语言训练-求s=a+aa+aaa+aaaa+aa...a的值 (C语言代码)浏览:613 |
C语言程序设计教程(第三版)课后习题6.3 (C++代码)浏览:963 |
The 3n + 1 problem (C语言代码)浏览:554 |