C++动态数组实现栈

//Implementation of stack using dynamic array
#ifndef STACK_H
#define STACK_H

#include <iostream>
using namespace std;

template<typename T> class Stack
{
public:
int stackTop;
int capacity;
T *arr;

bool isEmpty()
{
if(stackTop == -1)
return true;
else
return false;
}
bool isFull()
{
if(size() == capacity)
return true;
else
return false;
}
int size()
{
return stackTop+1;
}
void push(T x)
{
if(isFull())
{
capacity <<= 1;
T *temparr = new T[capacity];
for(int i=0;i<size();i++)
temparr[i] = arr[i];
delete[] arr;
arr = temparr;
}
stackTop += 1;
arr[stackTop] = x;
}
T pop()
{
if(!isEmpty())
{
stackTop -= 1;
return arr[stackTop+1];
}
else
{
cout<<"Stack underflow!"<<endl;
return NULL;
}
}
T getTop()
{
if(!isEmpty())
{
return arr[stackTop];
}
else
{
cout<<"Stack is empty!"<<endl;
return NULL;
}
}
void show()
{
if(isEmpty())
{
//cout<<"Stack is empty!"<<endl;
}
else
{
for(int i=0;i<size();i++)
cout<<arr[i]<<" ";
cout<<endl;
}
}
Stack()
{
capacity = 10;
arr = new T[capacity];
stackTop = -1;
}
Stack(int cap)
{
if (cap<=0)
{
cout<<"Capacity should be positive! Initialize the stack by default."<<endl;
capacity = 10;
}
else
{
capacity = cap;
}
arr = new T[capacity];
stackTop = -1;
}
~Stack()
{
delete[] arr;
}
};
#endif

posted @ 2013-06-08 15:39  肖恩吃青草  阅读(284)  评论(0编辑  收藏  举报