template<class _Ty, size_t _n> class line_stack {
private:
_Ty* a, * _top;
public:
//构造函数
line_stack() { a = new _Ty[_n]; _top = a - 1; }
//判空
bool empty() const { return _top == a - 1; }
//入栈
void push(_Ty&& _value) { ++_top; *_top = _value; }
//出栈
void pop() { --_top; }
//返回栈顶元素
_Ty& top() const { return *_top; }
//获得栈的大小
size_t size() const { return _top - a + 1; }
};
template<class _Ty> class link_stack {
private:
struct node { _Ty value; node* next; };
node* t, * p; size_t _size;
public:
//构造函数
link_stack() { _size = 0; t = nullptr; }
//判空
bool empty() const { return !_size; }
//入栈
void push(_Ty&& _value) { p = t; t = new node(); t->value = _value; t->next = p; ++_size; }
//出栈
void pop() { p = t->next; delete t; t = p; --_size; }
//返回栈顶元素
_Ty& top() const { return t->value; }
//获得栈的大小
size_t size() const { return _size; }
};
参考测试代码:
#include<iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//line_stack<int, 64> s;
link_stack<int> s;
cout << boolalpha << s.empty() << endl;
s.push(1);
cout << s.size() << endl << boolalpha << s.empty() << endl;
s.push(2); s.push(3); s.push(4); s.push(6);
cout << s.top() << endl << s.size() << endl;
s.pop(); s.pop(); s.pop(); s.pop(); s.pop();
cout << s.empty() << endl << s.size() << endl;
return 0;
}