c++学了类 老师就让写了这个、、、
#include
#include
using namespace std;
class Stack
{
public:
void push(int x);
void init();
int pop();
struct stack
{
int num;
stack *next ,*pre;
}*head;
};
//初始化栈顶
void Stack::init()
{
head=(struct stack *)malloc(sizeof(struct stack));
head->num=-1;
head->next=NULL;
head->pre=NULL;
}
//入栈
void Stack::push(int x)
{
stack *p;
p=(struct stack *)malloc(sizeof(struct stack));
head->next=p;
p->pre=head;
head=p;
head->num=x;
}
//出栈
int Stack::pop()
{
if(head->pre!=NULL)
{
int x=head->num;
head=head->pre;
head->next=NULL;
return x;
}
else
{
return 0x3fffffff;
}
}
int main()
{
Stack s;
s.init();
while(true)
{
cout<<"向栈中添加元素请按1,取出栈顶元素请按2,退出请按3"<>x;
if(x==1)
{
int y;
cout<<"请输入入栈的元素:";
cin>>y;
s.push(y);
cout<<"入栈成功!!"<
运行结果: