#include<iostream>
#include"stdlib.h"
using namespace std;
#definestack_init_size 100
#definestackincrement 10
typedef int selemtype;
typedef int status;
typedef struct{
selemtype *base;
selemtype *top;
int stacksize;
}sqstack;
statusinitstack(sqstack &s)
{
s.base =(selemtype *)malloc(stack_init_size* sizeof(selemtype));
if(!s.base)exit(0);
s.top=s.base;
s.stacksize = stack_init_size;
return 1;
}
voidcreate_sqstack(sqstack &s)
{
int i,n;
cout<<"请输入栈的长度:"<<endl;
cin>>n;
cout<<"请输入栈中的元素:"<<endl;
for(i=0;i<n;i++){
cin>>s.top[i];}
s.top=s.base;
for(i=0;i<n;i++){
s.top=s.top+1;}
}
status push(sqstack&s,selemtype e)
{
if(s.top-s.base>=s.stacksize){
s.base=(selemtype *)realloc(s.base,(s.stacksize+stackincrement)*sizeof(selemtype));
if(!s.base)exit(0);
s.top=s.base+s.stacksize;
s.stacksize+=stackincrement;}
*s.top++=e;
return 1;
}
status pop(sqstack&s,selemtype &e)
{
if(s.top==s.base)return 0;
e= *--s.top;
陪宴汪return 1;
}
statusstackempty(sqstack s)
{
if(s.top==s.base)
return 0;
else
return 1;
}
void conversion(int n)
{
sqstack s;int e ;
initstack(s);
while(n){
push(s,n%2);
n=n/2;}
cout<<"二进制数:"<<endl;
while(stackempty(s))
{pop(s,e);
cout<<e;}
cout<<endl;
}
void main()
{ sqstack s;int i,e,*p,n;
initstack(s);
create_sqstack(s);
cout<<"插祥宏入元素为:"<<endl;
cin>芦仔>e;
push(s,e);
p=s.top;
s.top=s.base;
cout<<"插入元素后的栈为:"<<endl;
for(i=0;i<p-s.base;i++){
cout<<*s.top<<" ";
s.top=s.top+1;}
cout<<endl;
pop(s,e);
p=s.top;
s.top=s.base;
cout<<"删除的栈顶元素为:"<<endl<<e<<endl;
cout<<"删除栈顶元素后的栈为:"<<endl;
for( i=0;i<p-s.base;i++){
cout<<*s.top<<" ";
s.top=s.top+1;}
cout<<endl;
cout<<"十进制数:"<<endl;
cin>>n;
conversion(n);
system("pause");
}
上学期正好做过。。