顺序栈实现十进制和八进制之间的转换
(1)首先实现栈的初始化,既申请固定大小的数组空间,存储数据,用到的方法是 int InitStack( struct sqstack *s );
(2)接下来就是让数据入栈 ,用到的方法是int push( struct sqstack *s,int e )
(3)与数据入栈相对应的是数据出栈,用到的方法是 int pop( struct sqstack *s,int *e )
(4)接下来的方法就是得到栈顶数据元素了,用到的方法是int get_top( struct sqstack *s)
(5)最后就是进行数制转换的核心算法了,用到的算法原理是
n = (n /d)*d+n % d;
实现的算法是void conversion(struct sqstack *s )
完整的实现代码如下所示:
#include<stdio.h> #include<stdlib.h> #include<malloc.h> #define MAX_SIZE 100 struct sqstack { int *base; int *top; int stack_size; }; int InitStack( struct sqstack *s ) { s->base = ( int *)malloc( MAX_SIZE ); if( s->base == NULL ) { return -1;} s->top = s->base ; s->stack_size = MAX_SIZE; return 1; } int push( struct sqstack *s,int e ) { if( s->top -s->base ==s->stack_size ) return -1; *s->top++ =e; return 1; } //出栈 int pop( struct sqstack *s,int *e ) { if( s->top == s->base ) return 0; e = --s->top; return 1; } //栈不为空,返回栈顶元素 int get_top( struct sqstack *s) { if( s->top == s->base ) exit(1); return *(s->top -1); } int stackempty( struct sqstack *s ) { if( s->top == s->base ) { return 0; } return 1; } void conversion(struct sqstack *s ) { InitStack(s); int n,*e; scanf("%d",&n); printf("%d=",n); while( n) { push( s,n%8 ) ; n =n/8; } printf("o"); while( stackempty( s ) ) { printf("%d",get_top(s)); pop(s,e); } } int main() { struct sqstack s,*m; m = &s; int i = InitStack( m ); conversion( m ); return 0; }