#include <iostream>
using namespace std;
template<class Datatype>
class Linkstack
{
public:
struct Node
{
Datatype data;
Node* next;
};
Linkstack();
Linkstack(const Datatype*, int);
~Linkstack();
bool Push(Datatype);
Datatype Pop();
private:
Node* top;
};
template<class Datatype>
Linkstack<Datatype>::Linkstack()
{
top = new Node;
top->next = NULL;
}
template<class Datatype>
Linkstack<Datatype>::Linkstack(const Datatype* a, int num)
{
top = new Node;
top->next = NULL;
int i = 0;
while (num--)
Push(a[i++]);
}
template<class Datatype>
Linkstack<Datatype>::~Linkstack()
{
while (top != NULL)
{
/* Node* temp = top;
top = top->next;
delete temp;
temp = NULL; */
Pop();
}
}
template<class Datatype>
bool Linkstack<Datatype>::Push(Datatype a)
{
Node* temp = new Node;
temp->data = a;
temp->next = top;
top = temp;
return true;
}
template<class Datatype>
Datatype Linkstack<Datatype>::Pop()
{
if (top != NULL)
{
Datatype x = top->data;
Node* temp = top;
top = top->next;
delete temp;
temp = NULL;
return x;
}
else
throw "Underflow";
}
int main()
{
char a[] = "hduwdhiqjojdiwqjodjwiq";
Linkstack<char> link_1(a, strlen(a) + 1);
link_1.Push('a');
cout << link_1.Pop() << endl;
return 0;
}
数据结构:栈部分——栈的链式存储
最新推荐文章于 2024-07-08 08:01:22 发布