20165303魏煜第十周课上补做

  • 在数据结构和算法中,排序是很重要的操作,要让一个类可以进行排序,有两种方法:
  • 有类的源代码,针对某一成员变量排序,让类实现Comparable接口,调用Collection.sort(List)
  • 没有类的源代码,或者多种排序,新建一个类,实现Comparator接口 调用Collection.sort(List, Compatator)

针对下面的Student类,使用Comparator编程完成以下功能:

  1. 在测试类StudentTest中新建学生列表,包括自己和学号前后各两名学生,共5名学生,给出运行结果(排序前,排序后)
  2. 对这5名同学分别用学号和总成绩进行增序排序,提交两个Comparator的代码
    import junit.framework.TestCase;
    import org.junit.Test;

import java.util.LinkedList;
import java.util.List;
import java.util.*;

public class TestStudent extends TestCase {
public static void main(String[] args) {
List

}
两个代码
import java.util.Comparator;
public class IDComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Student st1 = (Student)o1;
Student st2 = (Student)o2;
return (Integer.parseInt(st1.getId())-Integer.parseInt(st2.getId()));
}
}
import java.util.Comparator;
public class scoreComparator implements Comparator {
@Override
public int compare(Object o1, Object o2) {
Student st1 = (Student)o1;
Student st2 = (Student)o2;
return (int) (st1.getTotalScore()-st2.getTotalScore());
}
}

  • 参见附件,补充MyList.java的内容,提交运行结果截图(全屏)
    课下推送代码到码云

import java.util.Iterator;

public class MyList {
public static void main(String[] args) {

    Node<Integer> S1 = new Node<Integer>(20165301, null);
    Node<Integer> S2 = new Node<Integer>(20165302, null);
    Node<Integer> S3 = new Node<Integer>(20165304, null);
    Node<Integer> S4 = new Node<Integer>(20165305, null);
    //把上面四个节点连成一个没有头结点的单链表
    S1.next = S2;
    S2.next = S3;
    S3.next = S4;
    //遍历单链表,打印每个结点的
    Node<Integer> s = S1;
    while (s != null) {
        System.out.println(s.data);
        s = s.next;
    }
    System.out.println();
    //把你自己插入到合适的位置(学号升序)
    Node<Integer> M = new Node<Integer>(20165303, null);
    s = S1;
    while (s != null) {
        if (s.data < 20165303 && s.next.data > 20165303) {
            M.next = s.next;
            s.next = M;
            break;
        }
        else {
            s = s.next;
        }
    }
    System.out.println();
    //遍历单链表,打印每个结点的
    s = S1;
    while (s != null) {
        System.out.println(s.data);
        s = s.next;
    }
    System.out.println();
    //从链表中删除自己
    s = S1;
    while (s != null) {
        if (s.next.data == 20165303) {
            s.next = s.next.next;
            break;
        }
        else {
            s = s.next;
        }
    }
    System.out.println();
    //遍历单链表,打印每个结点的
    s = S1;
    while (s != null) {
        System.out.println(s.data);
        s = s.next;
    }
}

}

课后习题

猜你喜欢

转载自www.cnblogs.com/Vventador/p/8999303.html
今日推荐