class Course {
private static final int NUL = -1;
private AGradeListNode[] nodes;
private int list;
private int free;
protected static class AGradeListNode {
protected float grade;
protected int next;
@Override
return "Student: " + this.student + " Grade: " + this.grade;
}
}
public Course(int maxNumStudents) {
this.nodes = new AGradeListNode[maxNumStudents];
for (int idx = 0; idx < maxNumStudents; idx++)
this.nodes[idx] = new AGradeListNode();
for (int idx = 1; idx < maxNumStudents; idx++)
this.nodes[idx - 1].next = idx;
this.nodes[maxNumStudents - 1].next = NUL;
this.list = NUL;
this.free = 0;
}
private int getNode() {
if (this.free == NUL)
int idx = this.free;
this.free = this.nodes[idx].next;
return idx;
}
public void addStudentGrade
(Object stu,
float grade
) { // Search for insertion point (i.e. between prevIdx and nextIdx)
int prevIdx = NUL;
int nextIdx = this.list;
while (nextIdx != NUL && this.nodes[nextIdx].grade >= grade) {
prevIdx = nextIdx;
nextIdx = this.nodes[nextIdx].next;
}
// Initialize and insert new node
int newIdx = getNode();
this.nodes[newIdx].student = stu;
this.nodes[newIdx].grade = grade;
this.nodes[newIdx].next = nextIdx;
if (prevIdx == NUL)
this.list = newIdx;
else
this.nodes[prevIdx].next = newIdx;
}
public void print() {
for (int idx = this.list; idx != NUL; idx = this.nodes[idx].next)
System.
out.
printf("%2d: %s%n", idx,
this.
nodes[idx
]); }
public static void main
(String[] args
) { Course course = new Course(10);
course.addStudentGrade("Student 1", 3f); course.print();
course.addStudentGrade("Student 2", 5f); course.print();
course.addStudentGrade("Student 3", 2f); course.print();
course.addStudentGrade("Student 4", 1f); course.print();
course.addStudentGrade("Student 5", 2f); course.print();
course.addStudentGrade("Student 6", 3f); course.print();
}
}