题目描述:(时间限制: 1Sec 内存限制: 128MB)
已有a、b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并,按学号升序排列。
输入:
第一行,a、b两个链表元素的数量N、M,用空格隔开。 接下来N行是a的数据 然后M行是b的数据 每行数据由学号和成绩两部分组成
输出:
按照学号升序排列的数据
样式输入:
2 3
5 100
6 89
3 82
4 95
2 10
样式输出:
2 10
3 82
4 95
5 100
6 89
思路:
这题的解法类似于C#中的结构体,只不过在Java中使用class题代struct,其中对于对象排序,有两种方法:第一种是自己写一个排序,第二种是使用系统的sort()方法,但是需要接接口。
代码块:
import java.util.Arrays;
import java.util.Scanner;
public class 信息合并{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
Student [] stu = new Student[m+n];
for(int i = 0; i < n+m; i++){
stu[i] = new Student();
stu[i].id = sc.nextInt();
stu[i].score = sc.nextInt();
}
Arrays.sort(stu);
for(int i = 0; i < n+m; i++){
System.out.println(stu[i].id+" "+stu[i].score);
}
}
}
class Student implements Comparable<Student>{
public int id;
public int score;
@Override
public int compareTo(Student stu) {
// TODO Auto-generated method stub
if(this.id > stu.id)return 1;
if(this.id < stu.id)return -1;
return 0;
}
}