直接调库写
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class Main {
static TreeSet<Student> tree = new TreeSet<Student>();
static int num;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
while(n-->0) {
tree.add(new Student(sc.nextInt(),sc.nextInt(),sc.nextInt()));
}
Iterator< Student> it = tree.iterator();
for(int i=0;i<5;i++) System.out.println(it.next());
}
}
class Student implements Comparable<Student>{
int id;
int YuWen,Count;
Student(int YuWen,int ShuXue,int YinYu){
this.id=++Main.num;
this.YuWen=YuWen;
this.Count=YuWen+ShuXue+YinYu;
}
public int compareTo(Student o) {
if(this.Count!=o.Count)return o.Count-this.Count;//这样写是降序
else {
if(this.YuWen!=o.YuWen)return o.YuWen-this.YuWen;
else return this.id-o.id;//id是要升序
}
}
public String toString() {
return this.id+" "+this.Count;
}
}
手写排序单链表,在插入元素时,有序插入
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class Main {
static TreeSet<Student> tree = new TreeSet<Student>();
static int num;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
while(n-->0) {
StudentLinked.add(new Student(sc.nextInt(),sc.nextInt(),sc.nextInt()));
}
Student stu = StudentLinked.head;
for(int i=0;i<5;i++) {
stu=stu.next;
System.out.println(stu);
}
}
}
class Student implements Comparable<Student>{
int id;
int YuWen,Count;
Student before,next;
Student(){}
Student(int YuWen,int ShuXue,int YinYu){
this.id=++Main.num;
this.YuWen=YuWen;
this.Count=YuWen+ShuXue+YinYu;
}
public int compareTo(Student o) {
if(this.Count!=o.Count)return o.Count-this.Count;//这样写是降序
else {
if(this.YuWen!=o.YuWen)return o.YuWen-this.YuWen;
else return this.id-o.id;//id是要升序
}
}
public String toString() {
return this.id+" "+this.Count;
}
}
class StudentLinked{
static Student head = new Student(),p;
static void add(Student s) {
p=head;
int flag=0;
while(p.next!=null) {
if(p.next.compareTo(s)>0) {s.next=p.next;p.next=s;flag=1;break;}
else p=p.next;
}
if(flag==0)p.next=s;
}
}