c++和数据结构 模拟栈的入栈和出栈

来源:互联网 发布:手机怎样投诉淘宝卖家 编辑:程序博客网 时间:2024/05/01 00:54

c++学了类   老师就让写了这个、、、

#include <iostream>#include <stdlib.h>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"<<endl; int x;cin>>x;if(x==1){int y;cout<<"请输入入栈的元素:";cin>>y;s.push(y);cout<<"入栈成功!!"<<endl;}if(x==2){int top=s.pop();if(top==0x3fffffff){cout<<"当前栈为空"<<endl;}else{cout<<"当前栈顶元素为: "<<top<<endl; }}if(x==3){break;}}return 0;}
运行结果:



1 0
原创粉丝点击