//【数据结构】用C++编写栈及基本操作(包括入栈,出栈,获得栈顶,摧毁,清空等等)
//头文件
#ifndef _SEQ_STACK_
#define _SEQ_STACK_
#include
using namespace std;
template
class SeqStack { public: SeqStack(size_t sz=INIT_SIZE) { capacity = sz > INIT_SIZE ? sz : INIT_SIZE; base = new Type[capacity]; top = 0; } ~SeqStack() { destory(); } public: bool empty() const //判断是否为空 { return(top == 0); } bool full()const //判断是否已满 { return(top >= capacity); } void push(const Type &x) //进栈 { if (full() ) { cout << "栈已满,不能插入。" << endl; return; } base[top++] = x; } void pop() //出栈 { top--; } bool getTop(Type &x) const //获得栈顶 { if (top == 0) return false; x = base[top - 1]; return true; } int length() const //求大小 { return top; } void clear() //清除 { top = 0; } void destory() //摧毁 { delete[]base; base = NULL; capacity = top = 0; } void show() const //显示 { if (empty() == 1) { cout << "栈为空" << endl; return; } for (int i=top-1; i >=0; i--) { cout << base[i]<
mystack; int select = 1; int Item; while (select) { cout << "**************************************" << endl; cout << "* [1] show [2] push *" << endl; cout << "* [3] pop [4] length *" << endl; cout << "* [5] clear [6] destory *" << endl; cout << "**************************************" << endl; cout << "请选择:>"; cin >> select; switch (select) { case 1: mystack.show(); break; case 2: cout << "请输入要插入的值(-1结束):>"; while (cin >> Item, Item != -1) { mystack.push(Item); } break; case 3: mystack.pop(); break; case 4: cout << "大小为:" << mystack.length()<
|