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

【c++习题】【17/4/13】stack

2017-05-08 18:32 579 查看
1、stack 模板、动态内存分配、析构

1
#include "stack2.cpp"

#include <iostream>
using namespace std;

int main()
{
// 测试int型
Stack<int> s1(5);
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
s1.push(5);
if(!s1.isEmpty()) cout << s1.pop() << endl;
cout << s1.pop() << endl;
cout << s1.pop() << endl;
cout << s1.pop() << endl;
cout << s1.pop() << endl;
cout << endl;

// 测试char型
Stack<char> s2(6);
if(!s2.isFull()) s2.push('a');
s2.push('b');
s2.push('c');
s2.push('d');
s2.push('e');
s2.push('f');
cout << s2.pop() << endl;
cout << s2.pop() << endl;
cout << s2.pop() << endl;
cout << s2.pop() << endl;
cout << s2.pop() << endl;
//cout << s2.pop() << endl;
return 0;
}

2

template <class T>
class Stack {
private:
T *sptr;
int size;
int Top;
public:
// 构造器
Stack()
{
sptr = new T[10];
size = 10;
Top = 0;
}
Stack(int n)
{
sptr = new T
;
size = n;
Top = 0;
}
// 析构函数
~Stack()
{
delete []sptr;
}
// push
void push(T i)
{
*(sptr++) = i;
++Top;
}
// pop
T pop()
{
return *(--sptr);
--Top;
}
bool isEmpty()
{
if (Top == 0)
return true;
return false;
}
bool isFull()
{
if (Top < size)
return false;
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: