May 6, 2014 at 4:40pm UTC
I'm trying to create a linked list to hold inventory info. When I go to add a new node for another item the item of every node is replaced with the new item. I can't seem to figure out how to get this fixed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
struct Node{
string item;
struct Node *next;
};
class Player{
struct Node *head, *current;
public :
Player();
string CheckInventory(void );
void AddItem(string);
void RemoveItem(string);
}hero;
Player::Player()
{
head = 0;
}
void Player::AddItem(string newItem)
{
current = head;
if (current != 0){
while (current->next != 0){
current = current->next;
}
current->next = new Node;
current = current->next;
current->item = newItem;
current->next = 0;
}
else {
head = new Node;
head->next = 0;
head->item = newItem;
}
}
string Player::CheckInventory(void )
{
current = head;
while (current != 0){
cout<< "[" << current->item << "] " ;
current = current->next;
}
}
int main(void )
{
cout<< "Adding Sword\n" ;
cin.get();
hero.AddItem("Sword" );
hero.CheckInventory();
cout<< "\n" ;
cin.get();
cout<< "Adding Food\n" ;
cin.get();
hero.AddItem("Food" );
hero.CheckInventory();
cout<< "\n" ;
cin.get();
cout<< "Adding Torch\n" ;
cin.get();
hero.AddItem("Torch" );
hero.CheckInventory();
cout<< "\n" ;
cin.get();
}
Last edited on May 6, 2014 at 4:44pm UTC
May 6, 2014 at 5:09pm UTC
Looks like it's working to me:
Adding Sword
[Sword]
Adding Food
[Sword] [Food]
Adding Torch
[Sword] [Food] [Torch]
Last edited on May 6, 2014 at 6:58pm UTC
May 6, 2014 at 5:13pm UTC
just figure it out. I had CheckInventory set to return a string when it should have been void.
Last edited on May 6, 2014 at 5:16pm UTC
May 6, 2014 at 7:01pm UTC
That should not have been the cause of your problem. You should have gotten a compiler warning at line 48 that nothing was being returned, but that would not have mattered since you never used the return value from CheckInventory().