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

时间:2019-07-03 05:06:37

标签: c++ linked-list nodes singly-linked-list

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

使用数组和向量时,排序已经可以完美地工作了,但是在链接列表的插入方面却遇到了麻烦。我的getLink()调用用于获取我的链接的函数,该链接为= 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的学生,但是我正在为那部分而苦苦挣扎。当我打印链接列表时,它实际上还会输出大约10个学生,而实际上他们大约是100个,并且顺序不正确。

1 个答案:

答案 0 :(得分:1)

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

  • 新元素的CGPA小于列表中所有元素的CPGA值。在这种情况下,学生必须附加在列表的末尾。
  • 该学生的CPGA大于列表中的所有元素:必须在列表的开头添加新元素
  • 该学生在两个现有元素之间具有CPGA。在这里,必须在新元素之间插入新元素。因此,您必须跟踪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);
        }
    }