Help on a linked list problem

Status
Not open for further replies.

Darkroman

Wise, Aged Ars Veteran
110
Hi guys, so I'm kinda new to the forums, but not to the site. I was hoping you could provide some direction on what to do for this particular exercise problem (self-learning c++ with the book 'Beginning C++ Through Game Programming'. Basically I have to make the code more efficient by adding in a pointer to the end of the linked list, but I'm not even sure how to set that up.

Exercise Question: The Lobby::AddPlayer() member function from the Game Lobby program is inefficient because it iterates through all of the player nodes to add a new player to the end of the line. Add an m_pTail pointer data member to the Lobby class that always points to the last player node in the line and use it to more efficiently add a player.

The code:
Code:
#include <iostream>
#include <string>

using namespace std;

class Player
{
public:
    Player(const string& name = "");
    string GetName() const;
    Player* GetNext() const;
    void SetNext(Player* next);

private:
    string m_Name;
    Player* m_pNext; // Pointer to next player in list
};

Player::Player(const string& name):
    m_Name(name),
    m_pNext(0)
{}

string Player::GetName() const
{
    return m_Name;
}

Player* Player::GetNext() const
{
    return m_pNext;
}

void Player::SetNext(Player* next)
{
    m_pNext = next;
}

class Lobby
{
    friend ostream& operator<<(ostream& os, const Lobby& aLobby);

public:
    Lobby();
    ~Lobby();
    void AddPlayer();
    void RemovePlayer();
    void Clear();

private:
    Player* m_pHead;
    Player* m_pTail; // Already added in the data member pointer. Just not sure what to do after.

};

Lobby::Lobby():
    m_pHead(0),
    m_pTail(0)
{}

Lobby::~Lobby()
{
    Clear();
}

void Lobby::AddPlayer()
{
    //create a new player node
    cout << "Please enter the name of the new player: ";
    string name;
    cin >> name;
    Player* pNewPlayer = new Player(name);

    /* This comment was added by me (Darkroman) The code below is the code in question. It already utilizes the m_pHead pointer as you can see, but each time you call 
       AddPlayer() it has to iterate through the list before it can be added at the end. How do I utilize m_pTail to just go straight to the end without a loop? */

    //if list is empty make head of list this new player
    if (m_pHead == 0)
    {
        m_pHead = pNewPlayer;
    }

    //otherwise find the end of the list and add the player there
    else
    {
        Player* pIter = m_pHead;
        while (pIter->GetNext() != 0)
        {
            pIter = pIter->GetNext();
        }
        pIter->SetNext(pNewPlayer);
    }
}

void Lobby::RemovePlayer()
{
    if (m_pHead == 0)
    {
        cout << "The game lobby is empty.   No one to remove!\n";
    }
    else
    {
        Player* pTemp = m_pHead;
        m_pHead = m_pHead->GetNext();
        delete pTemp;
    }
}

void Lobby::Clear()
{
    while (m_pHead != 0)
    {
        RemovePlayer();
    }
}

ostream& operator<<(ostream& os, const Lobby& aLobby)
{
    Player* pIter = aLobby.m_pHead;

    os << "\nHere's who's in the game lobby:\n";
    if (pIter == 0)
    {
        os << "The lobby is empty.\n";
    }
    else
    {
        while (pIter != 0)
        {
            os << pIter->GetName() << endl;
            pIter = pIter->GetNext();
        }
    }

    return os;
}

int main()
{
    Lobby myLobby;
    int choice;

    do
    {
        cout << myLobby;
        cout << "\nGAME LOBBY\n";
        cout << "0 - Exit the program.\n";
        cout << "1 - Add a player to the lobby.\n";
        cout << "2 - Remove a player from the lobby.\n";
        cout << "3 - Clear the lobby.\n";
        cout << endl << "Enter choice: ";
        cin >> choice;

        switch (choice)
        {
            case 0: cout << "Good-bye.\n"; break;
            case 1: myLobby.AddPlayer(); break;
            case 2: myLobby.RemovePlayer(); break;
            case 3: myLobby.Clear(); break;
            default: cout << "That was not a valid choice.\n";
        }
    }
    while (choice != 0);

    return 0;
}
 

Blacken00100

Ars Legatus Legionis
10,130
Subscriptor
Your problem here is deeper than your linked list. You're using a poor reference book that's doing you a couple of disservices:

-I think it's probably the first time you're learning to program. I would rethink using this approach in general. Game programming, while fun (I do it), is probably not where you want to start to learn how to program.

-I find its pedagogy suspect just from this single example. A game lobby is not a list. A game lobby _has_ a list of players, which, in C++, will generally be modeled with an std::vector (an auto-resizing array) or an std::list (a linked list). Similarly, a Player class is not a list node; a list node has a Player to which it refers, it is not a player. (Learning to write your own linked list is valuable, but a book that wants you to immediately apply it to a real-world scenario regardless of its correctness is probably a dangerous book.)


I realize this isn't answering your specific question, but I would recommend taking a step back and re-evaluating what you're doing in general. I'm somewhat out of practice with C++ so I can't really give you a good recommendation there, but I'm sure somebody else probably can.
 

Darkroman

Wise, Aged Ars Veteran
110
Yes, I am a programming novice, but I've been going off and on with C++ for a while now. I've read this book before, done the exercises (except this one), and read other C++ books as well. This problem though has been stuck with me for a long time now (even after I stopped). I just think I'm missing something here. I don't understand how to get to the end of the list without using some kind of loop when entering a new 'player'. How can I just go to the end of the list?
 

MilleniX

Ars Tribunus Angusticlavius
8,139
Subscriptor++
You would probably be much better served by this book. However, with that said, if you've made it through all the exercises in your current book except this one, you've done quite well*. Alternately, if you're mostly comfortable with C++ programming at this point, maybe a book on algorithms and data structures might be a good step up. The particular issue you're facing would be covered in section 1.3, according to a reviewer's detailed table of contents.

Anyway, about your problem, let's break it down to some smaller pieces
1. You've already got its declaration done
2. You've got it initialized in the Lobby constructor
3. There are two cases in AddPlayer
3a. What should happen when it's the first player added?
3b. Assume you've got the tail pointer assigned correctly, what player does the loop in the case where you'd adding subsequent players stop on?

* Unless the exercises offered are utterly mindless, which I doubt. I much more strongly expect that they're too hard and pedagogically ill-suited. In that case, you've done even better by overcoming their likely shoddy work.
 

Darkroman

Wise, Aged Ars Veteran
110
I've figured it out through painstakingly going through how the program itself works in the memory (keeping track of it in my mind I should add...). The biggest thing I had trouble with were the functions "GetNext()" and "SetNext()". Those functions, for some reason, were just a bit off-putting, (probably because of the order they were put in... just threw me off for a loop, no pun intended). It seems so simple now! SetNext's function was to assign the address of the newly created object into the m_pNext data member function, GetNext's function was to return the address value of m_pNext. After figuring that out I came up with this.

Code:
void Lobby::AddPlayer()
{
    //create a new player node
    cout << "Please enter the name of the new player: ";
    string name;
    cin >> name;
    Player* pNewPlayer = new Player(name);

    //if list is empty make head of list this new player
    if (m_pHead == 0)
    {
        m_pHead = pNewPlayer; // Assigns the first instance's address to the m_pHead data member
        m_pTail = m_pHead; // Assigns m_pTail to the address of the first instance's address
    }

    //otherwise find the end of the list and add the player there
    else
    {
        m_pTail->SetNext(pNewPlayer); // Since m_pTail was assigned to be the first instance's address, m_pTail can call the Player class' member functions
                                      // Assigns the new object's address to the prior object's m_pNext data member
        m_pTail = m_pTail->GetNext(); // Assigns m_pTail to the address of the new object's m_pNext's data member
    }
}

After figuring this out (the extra comments were typed in by me to remember the steps), and seeing if it would work and found that it did, I was surprised a little. I thought that using a member function outside of its class wasn't allowed. m_pTail is from the Lobby class, but when I did m_pTail->SetNext(pNewPlayer), I guess it's because m_pTail was assigned to m_pHead in the first created instance. ... After typing that out it seems to make sense now. A lot to keep track of, plus I now know more about the use of those kinds of assignments. Just another roadblock in my mind that set me back.

Edit: Edited my comments on the new added code above to reflect my new understanding. It really doesn't seem very intuitive in the slightest... :-/
 

Dracorat

Ars Tribunus Militum
2,798
I'm not entirely sure your comments are correct.

The correct comments should go something like this:

Code:
    //otherwise the list already contains at least one member
    else
    {
        m_pTail->SetNext(pNewPlayer); // m_pTail is the end of the list, so add this item to the "next"
                                      // thus creating one more item on the end of the list
        m_pTail = m_pTail->GetNext(); // And move our pointer for the end of the list (m_pTail) to point at the
                                      // true end of the list which is that item.
    }
 

queelius

Seniorius Lurkius
13
As JoeJoe indicated, it can be very helpful to draw pictures, especially when dealing with pointers.

Another suggestion: when it comes to these sort of pointer-based structures, "end" nodes, like head and tail nodes, typically need special treatment. This special treatment can often be avoided if you use "dummy" nodes. That is, when inserting your first "real" node into an empty list (i.e., only contains the dummy head and tail nodes), no special treatment of it is required. It's the same as operating on a non-empty list.

Specifically:
Code:
// list constructor
List::List()
{
    head = new Node()
    tail = new Node()
    head->next = tail
    tail->prev = head
}

So, if you want to insert at a point in the list after a specific node:

Code:
void List::insert(Node* newNode, Node* after)
{
    // skipping throwing exceptions/catching errors in arguments
    newNode->prev = after
    newNode->next = after->next
    after->next->prev = newNode
    after->next = newNode
}

If you want to insert at the front of the list:

Code:
void List::prepend(Node* newNode)
{
    insert(newNode, head)
}

If you want to insert at the end of the list:

Code:
void List::append(Node* newNode)
{
    insert(newNode, tail)
}

I will usually try to devote a little time to doing things like this (dummy nodes) to avoid more tricky logic in my code.
 
Status
Not open for further replies.