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

时间:2023-03-09 19:16:46
【c++习题】【17/4/13】stack

1、stack 模板、动态内存分配、析构

#include "stack2.cpp"

#include <iostream>
using namespace std; int main()
{
// 测试int型
Stack<int> s1();
s1.push();
s1.push();
s1.push();
s1.push();
s1.push();
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();
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 ;
} template <class T>
class Stack {
private:
T *sptr;
int size;
int Top;
public:
// 构造器
Stack()
{
sptr = new T[];
size = ;
Top = ;
}
Stack(int n)
{
sptr = new T[n];
size = n;
Top = ;
}
// 析构函数
~Stack()
{
delete []sptr;
}
// push
void push(T i)
{
*(sptr++) = i;
++Top;
}
// pop
T pop()
{
return *(--sptr);
--Top;
}
bool isEmpty()
{
if (Top == )
return true;
return false;
}
bool isFull()
{
if (Top < size)
return false;
return true;
}
};