栈的应用:十进制转八进制

PS:数据结构 48页栈的应用

十进制转换八进制

自己写了下。供大家参考,通过源码进一步学习数据结构。

 

此书全部给出算法思想

要自己多动手敲敲code,不能光看不敲,那是没用的,给你思路,你也照样写不出来

要做一个合格的程序员就努力的写代码。通过代码量反映你的能力

 

 

//
利用栈实现进制间的转换


#include
<
stdio.h
>

#include

<
stdlib.h
>


//
#include<malloc.h>


#include
<
conio.h
>


#define
 STACK_INIT_SIZE   100


#define
 STACKINCREMENT    10

typedef 

struct
{
    

int
 
*
base
;
    

int
 
*
top;
    

int
 stacksize;
}SqStack;

int
 InitStack(SqStack 
&
S)
//
构造空栈


{
    S.

base
 
=
 (
int
 
*
)malloc(
sizeof
(
int

*
 (STACK_INIT_SIZE));
    

if
(
!
S.
base
) exit(

1
);
    S.top 

=
 S.
base
;
    S.stacksize 

=
 STACK_INIT_SIZE;
    

return
 
1
;
}

int
 Push(SqStack 
&
S, 
int
 e)
//
压栈


{
    

if
(S.top 

 S.
base
 
>=
 S.stacksize)
    {
    S.

base
 
=
 (
int
 
*
)realloc(S.
base

sizeof
(
int

*
 (STACK_INIT_SIZE 
+
 STACKINCREMENT));
    

if
(
!
S.
base
) exit(

1
);
    S.top 

=
 S.
base
 
+
 S.stacksize;
    S.stacksize 

+=
 STACKINCREMENT;
    }
    

*
S.top
++
 
=
 e;
    

return
 
1
;
}

int
  StackEmpty(SqStack S)
//
查看栈是否为空


{
    

if
(S.
base
 
==
 S.top) 
return
 
1
;
    

else
 
return
 
0
;
}

int
  Pop(SqStack 
&
S, 
int
 
&
e)
//
出栈


{
    

if
(S.top 
==
 S.
base

return
 
0
;
    e 

=
 
*–
S.top; 
    

return
 
1
;
}

void
 conversion()
//
将十进制用栈转化为八进制


{
    SqStack S;
    

int
 N;
    

int
 e;
    InitStack(S);
    printf(


输入N的值:

);
    scanf(


%d

,
&
N);
    printf(


转换后的值:

);
    

while
(N)
    {
        Push(S, N 

%
 
8
);
        N 

=
 N
/
8
;
    }
    

while
(
!
StackEmpty(S))
    {
        Pop(S,e);
        printf(


 %d

,e);
    }
}

void
 main()
{
    conversion();
    getch();
}

 

    原文作者:进制转换
    原文地址: https://blog.csdn.net/chlaws/article/details/1940709
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞