c++中如何用模版类定义链式堆栈,(最好用完整的程序举例)。
2个回答
展开全部
随手写了一个,楼主可自己去琢磨
#include<iostream>
using namespace std;
template<class T>
class LinkStack{
public:
LinkStack()
{
top=NULL;
}
~LinkStack()
{}
void SetEmpty()
{
node *temp;
while(top != NULL)
{
temp = top;
top=top->next;
delete temp;
}
}
bool IsEmpty()
{
return (top == NULL);
}
bool Push(T t)
{
node *temp = new node();
if(temp == NULL)
return false;
temp->data = t;
temp->next = top;
top = temp;
return true;
}
T Pop()
{
if(IsEmpty())
{
cout<<"stack is empty!"<<endl;
return 0;
}
T a=top->data;
node *temp= top;
top=top->next;
delete temp;
return a;
}
private:
struct node{
T data;
node *next;
};
node *top;
};
int main()
{
LinkStack<double> p;
p.Push(2.2);
p.Push(3.3);
p.Push(4.4);
cout<<p.Pop()<<"\t";
cout<<p.Pop()<<"\t";
cout<<p.Pop()<<endl;
p.Push(2.2);
p.Push(3.3);
p.Push(4.4);
p.SetEmpty();
cout<<p.Pop()<<endl;
return 0;
}
#include<iostream>
using namespace std;
template<class T>
class LinkStack{
public:
LinkStack()
{
top=NULL;
}
~LinkStack()
{}
void SetEmpty()
{
node *temp;
while(top != NULL)
{
temp = top;
top=top->next;
delete temp;
}
}
bool IsEmpty()
{
return (top == NULL);
}
bool Push(T t)
{
node *temp = new node();
if(temp == NULL)
return false;
temp->data = t;
temp->next = top;
top = temp;
return true;
}
T Pop()
{
if(IsEmpty())
{
cout<<"stack is empty!"<<endl;
return 0;
}
T a=top->data;
node *temp= top;
top=top->next;
delete temp;
return a;
}
private:
struct node{
T data;
node *next;
};
node *top;
};
int main()
{
LinkStack<double> p;
p.Push(2.2);
p.Push(3.3);
p.Push(4.4);
cout<<p.Pop()<<"\t";
cout<<p.Pop()<<"\t";
cout<<p.Pop()<<endl;
p.Push(2.2);
p.Push(3.3);
p.Push(4.4);
p.SetEmpty();
cout<<p.Pop()<<endl;
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询