根据id号将学生插入到列表中



所以我正在研究一种方法,我有点困惑,关键是将学生放入基于id号的列表中,因此id号较低的学生优先等等…我很困惑在我的if语句中做什么,一旦我检查它是否更大。

我现在的代码是
public boolean insort(StudentIF s) {
    StudentLLNode curr = head;
    if (s == null) {
        return false;
    }
    if (head == null) {
        StudentLLNode student = new StudentLLNode(s);
        head = student;
        size++;
        //System.out.println("working");
        return true;
    } else {
        if (curr.getStd().compareTo(s) == 0) {
            //System.out.println("working");
            return false;
        }
        while (curr.getNext() != null) {
            if(s.compareTo(curr.getStd()) == 1){
                //confused here 
            }
            curr = curr.getNext();
        }
        //confused here
        StudentLLNode student1 = new StudentLLNode(s);
        curr.setNext(student1);
        size++;
        return true;
    }
}

我的比较方法是

public int compareTo(StudentIF other) {
    if (other == null) {
        return 1;
    } // satisfies null student
    if (this.id > other.getId())
        return 1;
    else if (this.id < other.getId())
        return -1;
    else
        return 0; // if it's neither smaller nor larger, it must be equal
}
int index = Collections.binarySearch(myStudentList, studentObject);
myStudentList.add(index < 0 ? -1 * (index + 1) : index, studentObject);
/* OR
if(index < 0)
    myStudentList.add(-1 * (index + 1), studentObject);
If you did not want to add duplicates
*/

二进制搜索返回studenttobject的索引,如果对象不在列表中,则返回-(insertIndex) - 1的索引。

相关内容

  • 没有找到相关文章

最新更新