以排序方式插入节点时遇到问题

Having trouble with inserting nodes in a sorted fashion

我有一个 linked 列表,我必须根据对象的字段之一将对象插入到 linked 列表中,我必须以正确的顺序将节点插入 linked 列表。

我在使用数组和向量时排序工作得很好,但在 linked 列表的插入方面遇到了问题。我的 getLink() 调用用于获取我的 link 的函数,即 = next.

void sortedInsert(DomNodePtr& head, string fName, string lName, float CGPA, int rScore,string prov){
     DomNodePtr here = head;
     DomNodePtr tempPtr;
     tempPtr = new DomNode(fName, lName, CGPA, rScore, prov, head);

     while (here->getCumGPA() > CGPA && here->getLink() != NULL){
     here = here->getLink();

     }
     if (here->getCumGPA() < CGPA){
         tempPtr->setLink(here->getLink());
         here->setLink(tempPtr);
     }
     else if (here->getCumGPA() > CGPA){
         here = tempPtr;
     }
}

基本上我希望累积 GPA 最高的学生比 CGPA 较低的学生排序更高。我知道我的部分问题是我没有插入 CGPA 较低的学生,但我正在为这部分而苦苦挣扎。当我打印 linked 列表时,它也会输出大约 10 个学生,而实际上他们大约有 100 个,而且他们的顺序不正确。

将新生插入列表时有以下三种情况:

  • 新元素的 CGPA 小于列表中所有元素的 CPGA 值。在这种情况下,学生必须附加到列表的末尾。
  • 学生的 CPGA 大于列表的所有元素:必须将新元素添加到列表的头部
  • 学生在两个现有元素之间有一个 CPGA。这里必须在那些 to 元素之间插入新元素。因此,您必须跟踪前一个元素的 CPGA 大于新元素的 CPGA。

    void sortedInsert(DomNodePtr& head, string fName, string lName, float CGPA, int rScore,string prov){
        DomNodePtr here = head;
        DomNodePtr tempPtr;
        tempPtr = new DomNode(fName, lName, CGPA, rScore, prov, head);
    
        DomNodePtr previous = NULL; // keeping track of the previous element
    
        while (here->getCumGPA() >= CGPA && here->getLink() != NULL){
            previous = here;
            here = here->getLink();
        }
        if (here->getLink() == NULL){
            // Insert new student at the end of the list
            // If CPGA is larger for all students in the list
    
            here->setLink(tempPtr);
        }
        else if (previous = NULL) {
            // The new student has the highest CGPA and
            // has to be added at the head of the list
            tempPtr->setLink(here);
        }
        else{
            // Insert the student between the current
            // and the previous elements of the list
    
            previous->setLink(tempPtr);
            tempPtr->setLink(here);
        }
    }