#include<iostream>
using namespace std;
template<class numtype>
class LinkStack
{
public:
LinkStack();
~LinkStack();
bool Push(numtype x); //声明 压栈 函数
bool Pop(numtype *x); //声明 弹栈 函数
bool IsEmpty(); //声明 判空 函数
bool IsFull(); //声明 判满 函数
bool GetTop(numtype *x); //声明 取栈顶元素 函数
private:
typedef struct node
{
numtype data;
struct node* next;
}LinkStackNode;
int MAX_SIZE;
LinkStackNode* L;
bool InitStack(); //声明 初始化 函数
bool ClearStack(); //声明 清除 函数
};
int main()
{
LinkStack<int>temp_int;
int x;
temp_int.Push(1);
temp_int.GetTop(&x);
cout << x << endl;
temp_int.Push(20);
temp_int.Pop(&x);
cout << x << endl;
temp_int.Pop(&x);
cout << x << endl << endl;
LinkStack<char>temp_char;
char y;
temp_char.Push('x');
temp_char.GetTop(&y);
cout << y << endl;
temp_char.Push('*');
temp_char.Pop(&y);
cout << y << endl;
temp_char.Pop(&y);
cout << y << endl << endl;
LinkStack<double>temp_double;
double z;
temp_double.Push(3.1415926);
temp_double.GetTop(&z);
cout << z << endl;
temp_double.Push(0.9999999);
temp_double.Pop(&z);
cout << z << endl;
temp_double.Pop(&z);
cout << z << endl << endl;
return 0;
}
template<class numtype>
LinkStack<numtype>::LinkStack()
{
InitStack();
MAX_SIZE = 50;
}
template<class numtype>
LinkStack<numtype>::~LinkStack()
{
ClearStack();
}
//定义 压栈 函数
template<class numtype>
bool LinkStack<numtype>::Push(numtype x)
{
if (IsFull() == true)
{
cerr << "栈已满!!!压栈错误!!!" << endl;
exit(1);
}
LinkStackNode* temp;
temp = new LinkStackNode;
if(temp == NULL)
return (false);
temp->data = x;
temp->next = L->next;
L->next = temp;
return (true);
}
//定义 弹栈 函数
template<class numtype>
bool LinkStack<numtype>::Pop(numtype *x)
{
if (IsEmpty() == true)
{
cerr << "栈已空!!!弹栈错误!!!" << endl;
exit(1);
}
LinkStackNode* temp;
temp = L->next;
if(temp == NULL)
return (false);
L->next = temp->next;
*x = temp->data;
free(temp);
temp = NULL;
return (true);
}
//定义 初始化 函数
template<class numtype>
bool LinkStack<numtype>::InitStack()
{
L = new LinkStackNode;
L->next = NULL;
if(L == NULL)
return (false);
else
return (true);
}
//定义 清除 函数
template<class numtype>
bool LinkStack<numtype>::ClearStack()
{
LinkStackNode *p = NULL;
while (L->next != NULL)
{
p = L->next;
L->next = p->next;
delete p;
p = NULL;
if (p != NULL)
return false;
}
return true;
}
//定义 判空 函数
template<class numtype>
bool LinkStack<numtype>::IsEmpty()
{
return (L->next == NULL? true:false);
}
//定义 判满 函数
template<class numtype>
bool LinkStack<numtype>::IsFull()
{
int num = 0;
LinkStackNode* p = L;
while(p->next != NULL)
{
p = p->next;
num++;
}
return (num == MAX_SIZE? true:false);
}
//定义 取栈顶元素 函数
template<class numtype>
bool LinkStack<numtype>::GetTop(numtype *x)
{
if(IsEmpty() == true)
{
cerr << "栈已空!!!取栈顶元素错误!!!" << endl;
exit(1);
}
else
{
*x = L->next->data;
return (true);
}
}
模板_栈
最新推荐文章于 2023-11-26 10:10:52 发布