#include
using namespace std;
typedef int T;
class Node
{
public:
T data;
Node* next;
};
class Stack
{
public:
Stack();
~Stack();
void Pushstack();
void Popstack();
void Showstack();
private:
Node* s;
};
Stack::Stack() //创建链栈
{
s = new Node;
if (s == NULL) {
cout << "内存分配失败!" << endl;
}
else {
s->next = NULL;
}
}
Stack::~Stack()
{
while (s->next) {
Node* ptemp = s;
s = s->next;
delete ptemp; //如果不用工作指针temp,则无法销毁断掉的结点
ptemp = NULL;
}
delete s;
s = NULL;
}
void Stack::Pushstack() //入栈
{
Node* pnew = new Node;
T e = 0;
cout << "请输入压入数据:" << endl;
cin >> e;
pnew->next = s;
pnew->data = e;
s = pnew;
}
void Stack::Popstack() //出栈
{
if (s->next!=NULL) {
cout << "出栈数值为:" << s->data << endl;
Node* ptemp = s;
s = s->next;
delete ptemp;
ptemp = NULL;
}
else {
cout << "空链栈" << endl;
}
}
void Stack::Showstack() //遍历栈
{
Node* ptemp = s;
cout << "链栈中的元素为:" << " ";
while (ptemp->next) {
cout << ptemp->data << " ";
ptemp = ptemp->next;
}
ptemp = NULL;
}
int main()
{
Stack S;
S.Pushstack();
S.Pushstack();
S.Pushstack();
S.Showstack();
S.Popstack();
S.Showstack();
system("pause");
return 0;
}
实现效果如下:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)