Created
October 7, 2014 20:39
-
-
Save tyleryasaka/fbc977c01aad0d3f0337 to your computer and use it in GitHub Desktop.
stack.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <class T> | |
Stack<T>::Stack(){ | |
top = -1; | |
max_size = 5; | |
data = new T[max_size]; | |
} | |
template <class T> | |
Stack<T>::Stack(int size){ | |
top = -1; | |
max_size = size; | |
data = new T[max_size]; | |
} | |
template <class T> | |
Stack<T>::Stack(const Stack<T>& s){ | |
max_size = s.max_size; | |
data = new T[max_size]; | |
top = 0; | |
while (top < s.top){ | |
data[top] = s.data[top]; | |
top++; | |
} | |
} | |
template <class T> | |
Stack<T>& Stack<T>::operator=(const Stack<T>& s){ | |
if(this != &s){ // if calling object and parameter are not the same object | |
if (max_size > 0) // deallocate space if there is space allocated | |
delete [] data; | |
//copy data structure | |
max_size = s.max_size; | |
data = new T[max_size]; | |
top = 0; | |
while (top < s.top){ | |
data[top] = s.data[top]; | |
top++; | |
} | |
} | |
return *this; | |
} | |
template <class T> | |
Stack<T>::~Stack(){ | |
if(max_size > 0) | |
delete [] data; | |
top = -1; | |
max_size = 0; | |
} | |
template <class T> | |
bool Stack<T>::IsEmpty()const{ | |
return top == -1; | |
} | |
template <class T> | |
bool Stack<T>::IsFull()const{ | |
return top == max_size-1; | |
} | |
template <class T> | |
bool Stack<T>::Push(T item){ | |
bool success = false; | |
if(!IsFull()){ | |
success = true; | |
data[++top] = item; | |
} | |
return success; | |
} | |
template <class T> | |
bool Stack<T>::Pop(T &item){ | |
bool success = false; | |
if (!IsEmpty()){ | |
success = true; | |
item = data[top--]; | |
} | |
return success; | |
} | |
template <class U> | |
ostream& operator<<(ostream& os, const Stack<U>& s){ | |
for (int i = 0; i <= s.top; i++) | |
os << s.data[i] << " "; | |
return os; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment