#include <iostream.h>
#include <conio.h>
template <class T>
class Stack {
public:
Stack (int=10);
~Stack() {delete[] stackPtr;}
int push (const T&);
int pop (T&);
int isEmpty() const;
int isFull() const;
private:
int size;
int top;
T *stackPtr;
};
template <class T>
Stack<T>::Stack(int s)
{
size = s > 0 && s < 1000 ? s : 10;
top = -1;
stackPtr = new T[size];
}
template<class T>
int Stack<T>::push (const T &item)
{
if (!isFull()) {
stackPtr[++top] = item;
return 1;
}
return 0;
}
template<class T>
int Stack<T>::pop (T &popValue)
{
if (!isEmpty()) {
popValue = stackPtr[top--];
return 1;
}
return 0;
}
template<class T>
int Stack<T>::isEmpty() const
{
return top == -1;
}
template<class T>
int Stack<T>::isFull() const
{
return top == size - 1;
}
int main()
{
Stack< float > floatStack( 5 );
float f = 1.1;
cout << "Pushing element ke floatStack\n";
while (floatStack.push(f)) {
cout << f << ' ';
f += 1.1;
}
cout << "\nStack penuh.. "
<< f << "\n\nPop elemen dari doubleStack\n";
while (floatStack.pop(f))
cout << f << ' ';
cout << "\nStack kosong..\n";
Stack< int > intStack;
int intValue = 1;
cout << "\nPushing element ke intStack\n";
while (intStack.push(intValue)) {
cout << intValue << ' ';
++intValue;
}
cout << "\nStack penuh.. " << intValue
<< "\n\nPop element dari intStack\n";
while ( intStack.pop(intValue))
cout << intValue << ' ';
cout << "\nStack kosong..\n";
getch();
return 0;
}
No comments:
Post a Comment