/*
function:sequence stack
created by : xilong
date: 2017.2.7
*/#include"iostream"#include<stdlib.h>#include<math.h>
using namespace std;
#define OK 1#define ERROR 0#defineTRUE1#defineFALSE0#define STACK_INIT_SIZE 20#define SARCKINCREMENT 10
typedef int Status;
typedef char Elemtype;
typedef struct
{
Elemtype *base;
Elemtype *top;
int stackSize;
} sqStack;
/*
function: initialize the stack
*/void Stack_Init(sqStack *s)
{
s->base = (Elemtype *)malloc(STACK_INIT_SIZE * sizeof(Elemtype));
if (!s->base)
{
exit(0);
}
s->top = s->base; // at the very begining, the top of the stack is as same as the base of the stack
s->stackSize = STACK_INIT_SIZE; // size of the stack
}
/*
function: push an element "e" into the top of the stack
*/
int Stack_Push(sqStack *s, Elemtype e)
{
if (s->top - s->base >= s->stackSize)
{
s->base = (Elemtype *)realloc(s->base, (s->stackSize + SARCKINCREMENT) * sizeof(Elemtype));
if (!s->base)
{
exit(0);
}
s->top = s->base + s->stackSize; // set the top of the stack because of using the function "realloc"(realloc==>malloc, copy)
s->stackSize = s->stackSize + SARCKINCREMENT; // set the maximal size of the stack
}
*(s->top) = e;
s->top++;
}
/*
function: pop the top element
*/
Status Stack_Pop(sqStack *s, Elemtype *e)
{
if (s->top == s->base) // empty stack
{
return ERROR;
}
*e =*--(s->top); // move the pointer top down first, then take away the top elementreturn OK;
}
/*
function: clear the stack
*/
Status Stack_Clear(sqStack *s)
{
s->base = s->top;
return OK;
}
/*
function: destory the stack
*/
Status Stack_Destory(sqStack *s)
{
int i;
for (i =0; i < s->stackSize; i++)
{
free(s->base);
s->base++;
}
s->base = s->top =NULL;
s->stackSize =0;
return OK;
}
/*
function: return the length of the stack
*/
int Stack_Length(sqStack s)
{
return(s.top - s.base);
}
void main()
{
Elemtype c;
sqStack s;
int len, i, sum=0;
Stack_Init(&s);
cout <<"请输入二进制数,输入#符号表示结束!"<< endl;
scanf_s("%c", &c);
while (c !='#')
{
Stack_Push(&s, c);
scanf_s("%c", &c);
}
getchar();
cout <<"打印当前容量:";
len = Stack_Length(s);
cout << len << endl;
cout <<"出栈顺序为:";
for (i =0; i < len; i++)
{
Stack_Pop(&s, &c);
cout << c <<" ";
sum=sum+ (c -48) * pow(2, i);
}
cout << endl;
cout <<"二进制转换成十进制为:";
cout <<sum<< endl;
system("pause");
}