开发者

shift operation in linked list

name

played games

score

Deep

5

540 (head)

Peter

34

455

Avijit

2

430

Pekka

4

310 (tail)

For the above linked list of player list, I want to sort list in ascending order when Avijit gets higher score than Peter. So its a shift operation in linked list. Can anyone help me to find out the problem in code below to do this operation. And any solution? Thanks.

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;
  开发者_StackOverflow社区      }
}


I think you want

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

to be

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


If this is not a homework and you are not trying to learn the intrinsics of algorithms on a linked list then you should

  1. use the standard library
  2. avoid using pointers when you don't need pointers

That said, to answer your question:

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);

I'm not sure why you want to use a list; if you have no specific concrete reason then you should probably use a vector. Otherwise, std::list has a sort() member:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜