Trouble With Linked List

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
Looks like it's working to me:


Adding Sword

[Sword]

Adding Food

[Sword] [Food]

Adding Torch

[Sword] [Food] [Torch]
Last edited on
just figure it out. I had CheckInventory set to return a string when it should have been void.
Last edited on
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().
Topic archived. No new replies allowed.