#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;
}
}
C++模板&栈
最新推荐文章于 2023-08-21 17:10:38 发布