A simpler version of a Stack list with comments:
//STACK LIST
//RULE:
//LIFO (Last In, First Out), opposite of a Queue List, FIFO (First In First Out)
#include <iostream>
using namespace std;
template< class T >
class Stack {
private:
int MAX;//control how big a stack can be
int top;//the top of the stack = the data that will be giong out
T* items;//item points to a T address
public:
Stack(int size){//set the size of the stack
MAX = size;
top = -1;//-1 because when user create the object there will be no "top" data, think of this as a rack
items = new T[MAX];//set the number of item the stack can have
}
~Stack(){ delete [] items; }// deletes the entire array/stack
void push(T c){
if(full()){//check if the full function is true
cout << "Stack Full!" << endl;
//return 1;
}
items[++top] = c;//if the stack istn full will put the "data" in the first array[++top]
}
T pop(){
if(empty()){
cout << "Stack Empty!" << endl;
//return 1;
}
return items[top--];//reason why you have top= -1 in the constructor;
//reduce redundant variable in this function. without top=-1, will need to make a variable that holds the item data
}
int empty(){ return top == -1; }
int full(){ return top+1 == MAX; }
};
int main(){
Stack<char> st(10);
//the letters 'A' - 'J'
for(int i = 65; i < 75; i++)
st.push(i);//as the I increment, so does the top
//remove all the data
for(int j = 0; j < 11; j++)
cout << st.pop() << endl;//as the J increment top in the the object decrements hence getting the "stack" link list (taking from the last one in first)
return 0;
}
No comments:
Post a Comment