【數據結構】【C++】線性棧和鏈棧

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章