Sunday, April 1, 2012

Modified the stack list in the textbook closer to gamer point of view:

//Queue List
//First in First out FIFO
#include <iostream>
using namespace std;

class monster {
    int damage;

    public:
    monster(int a=0):damage(a){}
    int pop(){
        return damage;
    }
};

struct wave {
    monster data;//creates a monster object when you make a wave object
    wave* _next;//points to the address of a wave object
    wave(const monster& a, wave* next):data(a), _next(next){}//constructor accepts a reference of a monster object and pointer that points to a wave object.
                                                            //will also initiate monster object 'a' and cast it to monster object 'data', will do the same with _next with next
};

class game {
    wave* _start;
    wave* _end;
    public:
    game(): _start(NULL), _end(NULL){}
    ~game (){
        wave* current;
        while (current = _start){
            _start = _start->_next;
            delete current;
        }
    }//~game()
    void add(int d){
        wave* p = new wave(d,0);//second parameter is 0 because in a Queue when you're adding it should be in the end, hence the _next value should be null
        if (_start)
            _end->_next=p;//if there is a _start the _end will have the new address
        else
            _start=p;//if there are no _start meaning this is the first one will assign the _start address to the new wave object
         _end = p;//regardless if there was a value for _start or not, assign the _end to the new object
    }
    monster rem(){//returns a monster object
        monster data;
        if (_start){
            wave* current=_start;
            data = _start->data;//assign the _start's monster object(data, inside wave class) with the new monster object (created in this function)
            _start=_start->_next;//assign the _start address to the _next _start address;
            delete current;
            if (!_start)//if the address of _start is NULL change the _end to NUll as well
                _end=NULL;
        }
        return data;
    }
    bool empty(){return _start == NULL;}
};

int main(){
    game d;//_start and _end has Null address

    //Push Data onto the queue
    d.add(3);
    d.add(30);
    d.add(10);
    d.add(50);

    //remove the first node
    d.rem();

    //pop off data off the queue
    while (!d.empty())
        cout << d.rem().pop() << endl;

    return 0;
}

No comments:

Post a Comment