标签:顺序栈
栈的定义以及对栈的操作在mystack.h中实现
//mystack.h代码
#ifndef MYSTACK_H
#define MYSTACK_H
template<class T>
class Mystack
{
public:
Mystack(int stackcapacity);
~Mystack();
bool Isempty();
T Top();
void Push(T item);
void Pop();
private:
T *stack;
int top;
int capacity;
};
//利用构造函数初始化栈的容量
template <class T>
Mystack<T>::Mystack(int stackcapacity)
{
capacity= stackcapacity;
stack=new T[capacity];
top=-1;
}
//利用析构函数清除栈
template <class T>
Mystack<T>::~Mystack()
{
delete []stack;
}
//元素进栈
template <class T>
void Mystack<T>::Push(T item)
{
if(top==capacity-1)
{
Changsize(stack,capacity,2*capacity);
capacity=2*capacity;
}
stack[++top]=item;
}
//访问栈顶元素
template <class T>
T Mystack<T>::Top()
{
if(!Isempty())
return stack[top];
}
//改变栈的容量
template <class T>
void Changsize(T *a,int oldsize,int newsize)
{
if(newsize<0) throw "new length must be >=0";
T *temp=new T[newsize];
int number=min(oldsize,newsize);
std::copy(a,a+number,temp);
delete []a;
a=temp;
}
//栈顶元素出栈
template <class T>
void Mystack<T>::Pop()
{
top=top-1;
}
template <class T>
bool Mystack<T>::Isempty()
{
return top==-1;
}
#endif
主函数如下:
// main.cpp代码
#include "mystack.h"
#include <iostream>
using namespace std;
int main()
{
Mystack<int> ST(20);
ST.Push(11);
ST.Push(12);
ST.Push(13);
int a=ST.Top();
cout<<"此时栈顶元素为"<<a<<endl;
ST.Pop();
int b=ST.Top();
cout<<"此时栈顶元素为"<<b<<endl;
system("pause");
}
标签:顺序栈
原文地址:http://blog.csdn.net/adminabcd/article/details/46519201