基本操作难度不大,可以画图来辅助实现代码,也可脑袋思考敲代码。
#include<iostream>
using namespace std;
typedef struct stacknode
{
int age;
linkstack next;
}stacknode ,*linkstack;//链栈只能在表头进行插入和删除。
void initialstack(linkstack& s)
{
s = NULL;
cout << "初始化成功" << endl;
}//栈顶指针赋为空
void emptystack(linkstack& s)
{
if (s == 0)
{
cout << "栈空" << endl;
}
else cout << "栈非空" << endl;
}
void push(linkstack& s)
{
int t;
linkstack p = new stacknode;
cout << "请输入新入栈元素" << endl;
cin >> t;
p->age= t;
p->next = s;
s = p;
}//链栈入栈操作;
void out(linkstack& s)
{
if (s == NULL)
{
cout << "该栈为空栈无元素操作失败" << endl;
}
else
{
cout << "删除元素为" << s->age << endl;
linkstack p = s;
s = s->next;
delete p;
}
}//链栈出栈操作
int getfirst(linkstack& s)
{
if (s != NULL)
return s->age;
else cout << "error" << endl;
return false;
}
//取栈顶元素
int main()
{
linkstack s;
initialstack(s);
emptystack(s);
push(s);
out(s);
cout << "栈顶元素为" << getfirst(s) << endl;
return 0;
}