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

转载于:https://www.cnblogs.com/sirui/archive/2013/06/08/3126895.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值