链接列表排序

时间:2014-08-12 08:36:42

标签: c++ linked-list iterator

我希望能够通过另一种方法(getPrice)进行排序,我的代码是:

void gameListType::sortAscending() {
    nodeType<gameType> *current;
    nodeType<gameType> *next;
    nodeType<gameType> *tempcurrent;
    nodeType<gameType> *tempnext;
    nodeType<gameType> *tempprev;
    nodeType<gameType> *prev;
    prev = first;
    current = first->link;
    next = current->link;
    while ( current->link !=NULL){
        if (current->info.getPrice() > next->info.getPrice())
        {
            tempcurrent =current;
            tempprev = prev;
            tempnext = next;
            tempcurrent ->link = tempnext->link;
            tempnext ->link= tempprev->link;
        }
        prev = prev ->link;
        current = current ->link;
        next = next->link;
    }
}

如何更改代码以便我可以根据getPrice()方法对节点进行排序?

1 个答案:

答案 0 :(得分:0)

使用谓词进行排序。

void gameListType::sort(std::function<bool(gameType, gameType)> predicate)
{
    nodeType<gameType> *current;
    nodeType<gameType> *next;
    nodeType<gameType> *tempcurrent;
    nodeType<gameType> *tempnext;
    nodeType<gameType> *tempprev;
    nodeType<gameType> *prev;
    prev = first;
    current = first->link;
    next = current->link;
    while ( current->link !=NULL) {
        if (predicate(current->info, next->info))
        {
            tempcurrent =current;
            tempprev = prev;
            tempnext = next;
            tempcurrent ->link = tempnext->link;
            tempnext ->link= tempprev->link;
        }
        prev = prev ->link;
        current = current ->link;
        next = next->link;
    }
}

// sort ascending
sort([](gameType const& t1, gameType const& t2) {return t1.getPrice() > t2.getPrice();});

// sort desscending
sort([](gameType const& t1, gameType const& t2) {return t1.getPrice() < t2.getPrice();});