链表中的班次操作

时间:2011-05-07 03:40:40

标签: c++


玩游戏
得分


5
540(头)

彼得
34个
455

Avijit
2
430

佩卡
4
310(尾巴)

对于上面的播放器列表链接列表,当Avijit得分高于Peter时,我想按升序对列表进行排序。所以它在链表中的转换操作。任何人都可以帮助我找到下面的代码中的问题来执行此操作。任何解决方案? 感谢。

void Player::update_statistics(int last_game_point)
{
    player_ptr currPtr = head; // Moving pointer
    player_ptr prevPtr = NULL; // Pointer to node before *currPtr
    //player_ptr head;                //  class variable in Player class
    //player_ptr selected_player;     //  class variable in Player class
    //player_ptr previous_player;     //  class variable in Player class 

    // update selected player's data
    cout<<++(selected_player->played_games);  // increase by 1 for last game
    selected_player->total_point=(selected_player->total_point)+last_game_point;

    if ((selected_player!=head) && (previous_player->total_point < selected_player->total_point)){
        previous_player->link = selected_player->link;

        // search for appropriate position
        while (currPtr->total_point > selected_player->total_point){
            prevPtr = currPtr;
            currPtr = currPtr->link;
        }

        if (currPtr==head)
            selected_player->link=head;
            head=selected_player->link;
        }
        else {
            previous_player->link=selected_player;
            selected_player->link=currPtr;
        }
}

2 个答案:

答案 0 :(得分:0)

我想你想要

else {
        previous_player->link=selected_player;
        selected_player->link=currPtr;
    }

else {
        prevPtr->link=selected_player;
        selected_player->link=currPtr;
    }

答案 1 :(得分:0)

如果这不是作业,而你不想在链表上学习算法的内在函数,那么你应该

  1. 使用标准库
  2. 避免在不需要指针时使用指针
  3. 那就是说,回答你的问题:

    struct record {
        std::string name;
        int games_played;
        int score;
    };
    
    bool lower_score(const record& a, const record& b)
    {
        return a.score < b.score;
    }
    
    // ...
    std::vector<record> records = the_records();
    std::sort(records.begin(), records.end(), lower_score);
    

    我不确定你为什么要使用列表;如果你没有具体的具体原因那么你应该使用矢量。否则,std::list有一个sort()成员:

    std::list<record> records = no_no_i_meant_those_records();
    records.sort(lower_score);