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; }
相关文章推荐
- 关于C/C++运行期库
- VTK_Learning_Day_Two_Basic_Syntax
- C语言解决约瑟夫问题算法
- C/C++动态二维数组的内存分配和释放
- C++ 11之 && 右值引用
- memmove和memcpy
- c++ 调用 exe
- C语言左值与右值的区别(C语言深度剖析读书笔记一)
- C++实现单例模式
- error C2440: '=' : cannot convert from 'void&n C语言
- c++ stl
- C++ string
- C++ I/O
- C++关键字
- C++标准库(预处理器)
- Effective C++学习笔记(Part One:Item 1-4)
- (C/C++)register关键字
- C语言排序:冒泡排序
- 【C语言的日常实践(十四)】constkeyword详细解释
- 将C#程序与调用的dll对应的C++源码联调的一种方法