/*------------------------------------------------------/
/ a stack to convert bin to dec /
/------------------------------------------------------*/
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
#define INTLEN 32
//---------construct a stack-------
struct Stack{
int * base;
int * top;
int stacksize;
};
//-------Init the stack--------------
bool InitStack(Stack &mystack)
{
mystack.base=(int *)malloc(INTLEN*sizeof(int));
if(!mystack.base)
{
exit(ERROR);
}
mystack.top=mystack.base;
mystack.stacksize = INTLEN;
return OK;
}//initStack
//---------is stack empty-?-----
bool StackEmpty(Stack S)
{
if(S.top==S.base)
{
return OK;
}
return ERROR;
}
//------get the top of the stack-------------
bool GetTop(Stack &mystack,int &e)
{
if(mystack.top==mystack.base)
{
return ERROR;
}
e=*(mystack.top-1);
return OK;
}
//-----push an element into the stack------
bool Push(Stack &mystack,int e)
{
if(!mystack.base)
{
exit(OVERFLOW);
}
*mystack.top++=e;
//equal to the follow two sentence
//*mystack.top=e;
//mystack.top++;
return OK;
}//Push
//----Pop an element from the stack-------
int Pop(Stack &mystack,int &e)
{
if(mystack.top==mystack.base)
{
return ERROR;
}
e=*--mystack.top;
//equal to the follow two sentence
// mystack.top--;
// e=*mystack.top;
return OK;
} //Pop
//-------------main function---------------------
void main()
{
int n=9;
Stack intstack;
//scanf("%d",n);
InitStack(intstack);
while(n){
Push(intstack,n%2);
n/=2;
}
while(!StackEmpty(intstack))
{
int e=0;
Pop(intstack,e);
printf("%d ",e);
}
}
本文介绍了一个使用栈来实现从二进制数转换为十进制数的算法。通过定义结构体来创建栈,并实现了初始化栈、判断栈是否为空、获取栈顶元素、压栈和弹栈等基本操作。
1099

被折叠的 条评论
为什么被折叠?



