解题思路:
注意事项:
参考代码:import java.util.*;
// 定义链表节点类
class Node {
int id; // 学号
int score; // 成绩
Node next; // 指向下一个节点的引用
// 构造方法
public Node(int id, int score) {
this.id = id;
this.score = score;
this.next = null;
}
}
public class T1052 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取a、b链表的元素数量N、M
int N = scanner.nextInt();
int M = scanner.nextInt();
scanner.nextLine(); // 吸收换行符
// 构建链表a
Node headA = buildLinkedList(scanner, N);
// 构建链表b
Node headB = buildLinkedList(scanner, M);
// 收集所有节点到列表中,方便排序
List<Node> nodeList = new ArrayList<>();
collectNodes(headA, nodeList);
collectNodes(headB, nodeList);
// 按学号升序排序
Collections.sort(nodeList, (n1, n2) -> n1.id - n2.id);
// 输出排序后的结果
for (Node node : nodeList) {
System.out.println(node.id + " " + node.score);
}
scanner.close();
}
/**
* 构建链表的工具方法
* @param scanner 输入扫描器
* @param count 链表节点数量
* @return 链表头节点
*/
private static Node buildLinkedList(Scanner scanner, int count) {
Node head = null;
Node current = null;
for (int i = 0; i < count; i++) {
int id = scanner.nextInt();
int score = scanner.nextInt();
Node newNode = new Node(id, score);
if (head == null) {
head = newNode;
current = newNode;
} else {
current.next = newNode;
current = newNode;
}
}
return head;
}
/**
* 将链表中的所有节点收集到列表中
* @param head 链表头节点
* @param nodeList 存储节点的列表
*/
private static void collectNodes(Node head, List<Node> nodeList) {
Node current = head;
while (current != null) {
nodeList.add(current);
current = current.next;
}
}
}
0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复