#include<iostream>
using namespace std;
template<typename T>
struct Node
{
T data;
Node<T>* next;
};
template<typename T>
class LinkStack
{
private:
Node<T>* top;
public:
LinkStack();
~LinkStack();
T Push(T n);
T Pop();
T GetTop();
int StackLength()const;
bool IsEmpty();
};
template<typename T>
LinkStack<T>::LinkStack()
{
top = new Node<T>;
top->next = nullptr;
}
template<typename T>
LinkStack<T>::~LinkStack()
{
delete[]top;
}
template<typename T>
T LinkStack<T>::Push(T n)
{
Node<T>* p = new Node<T>;
if (!p)
{
throw "ERROR";
}
else
{
p->data = n;
p->next = top->next;
top->next = p;
return n;
}
return n;
}
template<typename T>
T LinkStack<T>::Pop()
{
Node<T>* p;
T temp;
if (top->next == nullptr)
{
return 0;
}
else
{
p = top->next;
temp = p->data;
top->next = p->next;
delete p;
}
return temp;
}
template<typename T>
T LinkStack<T>::GetTop()
{
T temp;
if (top->next == nullptr)
{
return 0;
}
else
{
temp = top->next->data;
}
return temp;
}
template<typename T>
int LinkStack<T>::StackLength() const
{
Node<T>* p = top->next;
int i = 0;
while (p != nullptr)
{
i++;
p = p->next;
}
return i;
}
template<typename T>
bool LinkStack<T>::IsEmpty()
{
if (top->next = nullptr)
{
return 1;
}
else
{
return 0;
}
}
/*
LinkStack();
~LinkStack();
T Push(T n);
bool Pop();
T GetTop();
int StackLength()const;
bool IsEmpty();
*/
int main()
{
LinkStack<int> Stack;
int T = 10;
while (T--)
{
Stack.Push(T);
}
cout << "top元素为: " << Stack.GetTop() << endl;
cout << "Stack的长度为:" << Stack.StackLength() << endl;
cout << "Pop的元素为: " << Stack.Pop() << endl;
cout << "top元素为: " << Stack.GetTop() << endl;
cout << "Stack的长度为:" << Stack.StackLength() << endl;
if (!Stack.IsEmpty())
{
cout << "Stack不为空" << endl;
}
else
{
cout << "Stack为空" << endl;
}
return 0;
}
数据结构-链式栈的实现
最新推荐文章于 2022-11-26 14:08:11 发布