用C++中的单链表进行插入排序

Insertion Sort with a Singly Linked List in C++

本文关键字:链表 插入排序 C++ 单链表      更新时间:2023-10-16

我正试图为LinkedList类编写一个方法,该方法将根据Person对象的名称对其链表进行排序。我的方法编译得很好,但当我尝试对人员列表进行排序时,输出是不正确的。它也从未停止运行。例如,这个代码

Person *p1 = new Person("K", "B");
Person *p2 = new Person("A", "A");
Person *p3 = new Person("S", "M");
Person *p4 = new Person("B", "M");
LinkedList ll;
ll.insertFront(*p1);
ll.insertFront(*p2);
ll.insertFront(*p3);
LinkedList newList = ll.insertionSort();
newList.print();
cout << endl;

给出此输出

B, K
A, A

有人能帮我找出我的算法哪里出了问题吗?谢谢

这是我用来按名字的第一个和最后一个排序的方法:

int Person::compareName(Person p)
{
    if (lName.compare(p.lName) > 0)
    {
        return 1;
    }
    else if (lName.compare(p.lName) == 0)
    {
        if (fName.compare(p.fName) > 0)
        {
            return 1;
        }
        else return -1;
    }
    else return -1;
}

插入排序方法:

LinkedList LinkedList::insertionSort()
   {
    //create the new list
    LinkedList newList;
    newList.front = front;
    
    Node *n;
    Node *current = front;
    Node *trail = NULL;
    
   for(n=front->link; n!= NULL; n = n->link)//cycle through old chain
{
    Node* newNode = n;
    
    //cycle through new, sorted chain to find insertion point
    for(current = newList.front; current != NULL; current = current->link)
    {
        //needs to go in the front
        if(current->per.compareName(n->per) < 0)
        {
            break;
        }
        
        else
        {
            trail = current;
            
        }
    }
    
    //if it needs to be added to the front of the chain
    if(current == front)
    {
        newNode->link = newList.front;
        newList.front = newNode;
    }
    //else goes in middle or at the end
    else{
        newNode->link = current;
        trail->link = newNode;
    }
    return newList;
}

您在内部for循环中有current->link,在else中有到内部for循环的链接。我假设您在for循环中确实有current=current->link,否则它什么都不做。如果是这样的话,你就会跳过其他所有元素。

你还有一个语言问题——你不是在创建新的节点,而是在改变原始列表上的节点。这意味着你在遍历列表时会更改列表,这会在排序时损坏列表。行为是未定义的,取决于添加元素的顺序。

即使在修复了任何链表处理问题(我还没有看过)之后,compareName()函数也有一个缺陷——在比较姓氏相同的Person对象时,它可能会从函数返回而不提供值(在Name.compare(p.fName) <= 0的情况下)。

从比较函数中得到一个不确定的结果几乎会破坏任何类型的结果

既然这可能是家庭作业,我就把批改这道题当作练习。