C++模板&栈

#pragma once
#include <iostream>
template <typename T1>
struct SLinkedList
{
	T1 value;
	SLinkedList<T1>* next;
	SLinkedList(const T1& item, SLinkedList<T1>* next_ = nullptr)//用于初始化data和next
	{
		value = item;
		next = next_;
	}
};

template <typename T2>
class Stack
{
private:
	SLinkedList<T2>* top;
	size_t length;
public:
	Stack();
	~Stack();

	void Push(T2 value_);
	void Pop(T2& value_);
	bool isEmpty();
	void display();
	size_t Length()
	{
		return this->length;
	}
};

template <typename T2>
Stack<T2>::Stack()
	:top {nullptr}, length{ 0 }
{}

template <typename T2>
Stack<T2>::~Stack()
{
	SLinkedList<T2>* temp = nullptr;
	while (top)
	{
		temp = top;
		top = top->next;
		delete temp;
		temp = nullptr;
	}
}

template <typename T2>
void Stack<T2>::Push(T2 value_)
{
	SLinkedList<T2>* newNode = new SLinkedList<T2>(value_);
	if (newNode)
	{
		newNode->next = nullptr;
		if (top == nullptr)
		{
			newNode->next = top;
			top = newNode;
			++length;
		}
		else
		{
			newNode->next = top;
			top = newNode;
			++length;
		}
	}
}

template<typename T2>
void Stack<T2>::Pop(T2 & value_)
{
	if (isEmpty())
	{
		std::cout << "stack is empty, can't pop...\n";
		std::exit(1);
	}
	else
	{
		value_ = top->value;
		SLinkedList<T2>* temp = top;
		top = top->next;
		delete temp;
		temp = nullptr;
		--length;
	}
}

template<typename T2>
bool Stack<T2>::isEmpty()
{
	if (top)
		return false;
	else
		return true;
}
template<typename T2>
void Stack<T2>::display()
{
	SLinkedList<T2>* temp = top;
	while (temp)
	{
		std::cout << temp->value << " ";
		temp = temp->next;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值