学习数据结构的栈之后,为了巩固加深对栈的理解,通过实现一个栈的操作来解决二进制数转十进制数的问题,压栈操作使用输入流cin来读入数据,cin会忽略回车符,因此不再需要getchar来对其进行回收,相比scanf会更加简洁方便,直接上代码:
#include"stdafx.h"
#include"stdlib.h"
#include"math.h"
#include<iostream>
using namespace std;
#define STACK_INIT_SIZE 20 //定义栈的初始大小
#define STACKINCREMENT 10 //增加栈容量
typedef char elemtype;
typedef struct
{
elemtype *top; //头部指针
elemtype *base; //底部指针
int stacksize;
}sqStack;
/****初始化栈****/
void InitStack(sqStack *s)
{
s->base = (elemtype *)malloc(STACK_INIT_SIZE * sizeof(elemtype));
if (!s->base)
{
exit(0);
}
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
}
/****压栈****/
void push(sqStack *s,elemtype e)
{
if (s->top - s->base >= STACK_INIT_SIZE)
{
s->base = (elemtype *)realloc(s->base, (STACK_INIT_SIZE + STACKINCREMENT) * sizeof(elemtype));
}
*(s->top) = e;
s-&