您的位置:首页 > 编程语言 > C语言/C++

C++实现顺序栈

2015-07-03 15:38 465 查看
VS2013下实现
#include <iostream>
#include <string>
using namespace std;

const int StackSize = 20;
template<typename T>
class Stack{
public:
Stack(){ top = -1; }    //构造函数,初始化一个空栈
Stack(T a[], int n);          //含参构造函数
Stack(const Stack<T> &otherstack);    //拷贝构造函数
Stack<T>& operator=(Stack<T> &otherstack);    //赋值函数,目标栈必须是非静态成员
~Stack(){ }             //析构函数
void Push(T x);           //入栈
T Pop();                 //出栈
T GetTop(){ if (top != -1) return data[top]; }   //取栈顶元素
string IsEmpty();    //是否为空栈
void Print();
void Clear();
private:
T data[StackSize];       //以数组形式存放栈元素
int top;                //栈顶指针,即数组下标
};

template<typename T>
Stack<T>::Stack(T a[], int n)
{
top = -1;
if (n <= StackSize)
for (int j = 0; j < n; ++j)
data[++top] = a[j];
}

template<typename T>
Stack<T>::Stack(const Stack<T> &otherstack)    //拷贝构造函数定义
{
top = -1;
int p = otherstack.top;
if (p < StackSize){          //判断本地栈是否可以容纳目标栈
while (p != -1)
{
data[++top] = otherstack.data[p--];
}
}
}

template<typename T>
Stack<T>& Stack<T>::operator=(Stack<T> &otherstack)        //赋值函数定义
{
//int p = top;
int q = otherstack.top;
if (this != &otherstack)
{
Clear();
while (q != -1)
{
data[++top] = otherstack.data[q--];
}
}
return *this;   //为了连续赋值,返回自身
}

template<typename T>
void Stack<T>::Push(T x)           //栈顶入栈操作,直接使用top
{
if (top == StackSize)
throw "上溢";
data[++top] = x;
}

template<typename T>
T Stack<T>::Pop()
{
if (top == -1)
throw "下溢";
return data[top--];
}

template<typename T>
string Stack<T>::IsEmpty()
{
if (top == -1)
return "空";
else
return "非空";
}

template<typename T>
void Stack<T>::Print()           //遍历输出栈元素,此时不能用top进行遍历,不然将top位置,影响后面的操作
{
int p = top;
while (p != -1)
cout << data[p--] << " ";
cout << endl;
}

template<typename T>
void Stack<T>::Clear()      //清空栈
{
while (top != -1)
{
Pop();
}
}

int _tmain(int argc, _TCHAR* argv[])
{
int a[] = { 1, 2, 3, 4, 5, 6 };
Stack<int> A(a,6);
A.Print();
A.Push(7);
A.Print();
cout<<A.Pop()<<endl;
A.Print();
cout << A.GetTop() << endl;
cout<< A.IsEmpty() << endl;
Stack<int> B(A);
B.Print();
A.Print();
A.Push(9);
B = A;
B.Print();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: