最近在从头开始研究数据结构与算法,将最近自己写的实例与大家分享,也希望大家多多提意见。
直接上代码:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 50
#define STACK_INCREMENT 20
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}sqStack;
void InitStack(sqStack *s)
{
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if( !s->base )
{
printf("STACK INIT FAILED!\n");
exit(0);
}
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
}
void Push(sqStack *s,ElemType e)
{
if(s->top - s->base >= s->stacksize)
{
s->base = (ElemType *)realloc(s->base, (STACK_INIT_SIZE + STACK_INCREMENT) * sizeof(ElemType)); //超出重新分配栈的大小
if( !s->base )
{
exit(0);
}
}
*s->top = e;
s->top++;
}
void Pop(sqStack *s,ElemType *e)
{
if(s->top == s->base)
{
printf("STACK IS EMPTY ,NO ELEMENT CAN BE POPPED!\n");
return;
}
*e = *--(s->top);
}
void ClearStack(sqStack *s)
{
if(s->top != s->base)
{
s->top = s->base;
}
}
int GetStackSize(sqStack *s)
{
return (s->top - s->base);
}
int main()
{
sqStack bin;
sqStack oct;
ElemType e,c_input;
int sum = 0;
int i = 0,j,stack_size_bin,stack_size_oct;
InitStack(&bin);
InitStack(&oct);
printf("please input a binary: end with '#' \n");
scanf("%c",&c_input);
while(c_input != '#')
{
Push(&bin,c_input);
scanf("%c",&c_input);
}
getchar();
stack_size_bin = GetStackSize(&bin);
while(i < stack_size_bin)
{
for(j = 0;j < 3;j++)
{
Pop(&bin, &e);
sum += (e - 48) * pow(2, j);
i++;
if(i >= stack_size_bin)
{
break;
}
}
Push(&oct, (char)sum);
sum = 0;
}
stack_size_oct = GetStackSize(&oct);
for(i = 0; i < stack_size_oct; i++)
{
Pop(&oct, &e);
printf("%c ",e + 48); //要注意ASCII码转换
}
return 0;
}