严蔚敏 吴伟明 数据结构 栈的基本操作实现 2,8,16数值转换
#include<stdio.h>#include<malloc.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define ERROR 0
#define OK 1
#define OVERFLOW -2
/********************************/
/**数值转换(适用于二,八,十六进制)
ZHAN.C
aothor.jiang 2010.4.20*/
/*********************************/
typedef struct{
int *base;
int *top;
int stacksize;
}sqstack;
void initstack(sqstack *s)
{s->base=(int *)malloc(STACK_INIT_SIZE*sizeof(int));
if(!s->base) exit(OVERFLOW);
s->top=s->base;
s->stacksize=STACK_INIT_SIZE ;
}
int destroystack(sqstack *s)
{if(!s->base) return ERROR;
free(s->base);
s->base=s->top=NULL;
s->stacksize=0;
return OK;
}
int clearstack(sqstack *s)
{if(!s->base) return ERROR;
s->top=s->base;
return OK;
}
int stackempty(sqstack s)
{return s.base==s.top;
}
int stacklength(sqstack s)
{return s.stacksize;
}
void gettop(sqstack *s,int *e)
{if(s->base==s->top) return;
*e=*(s->top-1);
}
void push(sqstack *s,int e)
{if(s->top-s->base>=s->stacksize)
{s->base=(int*)realloc(s->base,(s->stacksize+STACKINCREMENT)*sizeof(int));
if(!s->base) exit(OVERFLOW);
s->top=s->base+s->stacksize;
s->stacksize+=STACKINCREMENT;
}
*(s->top++)=e;
}
void pop(sqstack *s,int *e)
{if(s->base==s->top) return;
*e=*(--s->top);
}
main()
{int n,base,e;
sqstack s;
initstack(&s);
printf("***********************\n");
printf("*****base=2/8/16*******\n");
printf("***********************\n");
printf("-----------------------\n");
printf("Please input n= ,base= \n");
printf("-----------------------\n");
scanf("n=%d,base=%d",&n,&base);
while(n)
{if(n%base<8)
{push(&s,n%base);n=n/base;}
else
{ switch(n%base)
{case 10: push(&s,'A');n=n/base;break;
case 11: push(&s,'B');n=n/base;break;
case 12: push(&s,'C');n=n/base;break;
case 13: push(&s,'D');n=n/base;break;
case 14: push(&s,'E');n=n/base;break;
case 15: push(&s,'F');n=n/base;break;
}
}
}
printf("-----------------------\n");
printf("after converted:new n=");
while(s.base!=s.top){
gettop(&s,&e);
if(e>=0&&e<=9)//不能用pop(&s)来判断,因为那样头指针会变。
{ pop(&s,&e);
printf("%d",e);
}
else {
pop(&s,&e);
printf("%c",e);
}
}
printf("\n");
printf("-----------------------\n");
/*scanf("%d",&n);
while(n)
{push(&s,n%8);n=n/8;}
while(s.base!=s.top)
{printf("%d",pop(&s));}
*/
}
/*我很珍惜每一份的努力,有着成就感的支持,我才能向前*/