簡単なstack実現
2785 ワード
#include <iostream>
#include <stdexpect>
#include <memory>
template<typename T>
class Node{
public:
T data; // .
Node<T>* next; // .
template<typename Ty>
Node(const Ty& data_, Node<T>* n=nullptr);
~Node()=default;
};
template<typename T>
template<typename Ty>
Node<T>::Node(const Ty& data_, Node<T>* n)
:data(data_)
next(n)
{
//
}
template<typename T>
class AStack{ // .
private:
unsigned int maxSize; // stack .
Node<T>* top; // .
Node<T>* rear; // .
unsigned int counter; // , stack .
void clear(Node<T>* root)noexcept; // stack .
public:
template<typename Ty, typename = std::enable_if< std::is_unsigned<Ty>::value>::type>
AStack(const Ty& size);
~AStack();
template<typename Ty>
void push(const Ty& value);
const Node<T>& top()const noexcept;
void pop()noexcept;
void clear()noexcept;
};
template<typename T>
template<typename Ty, typename>
AStack<T>::AStack(const Ty& size)
:maxSize(size), //size
top(nullptr), // 。
rear(nullptr),
counter(0)
{
//
}
template<typename T>
AStack<T>::~AStack()
{
this->clear();
}
template<typename T>
void AStack<T>::clear(Node<T>* ptr)noexcept
{
if(ptr == nullptr){
return;
}
if(ptr != nullptr){
this->clear(ptr->next);
}
delete ptr;
ptr = nullptr;
}
template<typename T>
const Node<T>& AStack<T>::top()const noexcept // stack .
{
return (this->rear)->data;
}
template<typename T>
void AStack<T>::pop()noexcept // stack .
{
Node<T>* headNext = (this->head)->next;
delete this->head;
this->head = headNext;
headNext = nullptr;
}
template<typename T>
void AStack<T>::push(const Ty& value) // stack.
{
if(this->head == nullptr){
++(this->counter); //this->counter = 1;
this->head = new Node<Ty>(value);
this->rear = (this->head)->next;
}else{
if(this->counter <= this->maxSize)
{
this->rear = new Node<Ty>(value);
this->rear = (this->rear)->next;
}else{
throw std::runtime_error("Can not bigger than the maxSize!");
}
}
}
template<typename T>
void AStack<T>::clear()noexcept
{
this->clear(this->head);
}