数据结构 栈应用(进制转换)

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <math.h>
 4 
 5 #define STACK_INIT_SIZE    10
 6 #define STACKINCREMENT    2
 7 #define    OK    1;
 8 #define FALSE 0;
 9 
10 typedef int Status;
11 typedef int SElemType;
12 
13 
14 typedef struct SqStack
15 {
16     SElemType    *base;
17     SElemType    *top;
18     int  stacksize;
19 }SqStack;
20 
21 Status InitStack(SqStack *S)
22 {
23     (*S).base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
24     if(!(*S).base)
25         exit(OVERFLOW);
26     (*S).top = (*S).base;
27     (*S).stacksize = STACK_INIT_SIZE;
28 }
29 
30 Status Push(SqStack *S,SElemType e)
31 {
32     if((*S).top - (*S).base >= (*S).stacksize)
33     {
34         (*S).base = (SElemType *)realloc((*S).base,((*S).stacksize + STACKINCREMENT) * sizeof(SElemType));
35         if(!(*S).base)
36             exit(OVERFLOW);
37         (*S).top = (*S).base + (*S).stacksize;
38         (*S).stacksize += STACKINCREMENT;
39     }
40     *((*S).top)++ = e;
41     return OK;
42 }
43 
44 Status StackEmpty(SqStack *S)
45 {
46     if ((*S).base == (*S).top)
47         return OK;
48     return FALSE;
49 }
50 
51 Status Pop(SqStack *S,SElemType *e)
52 {
53     if ((*S).base == (*S).top)
54         return FALSE;
55     *e = *--(*S).top;
56     return OK;
57 }
58 void conversion()
59 {
60     SqStack S;
61     SElemType N;
62     SElemType e;
63     InitStack(&S);
64     printf("请输入十进制数:");
65     scanf("%d",&N);
66     printf("%d转换为8进制为:",N);
67     while (N)
68     {
69         Push(&S,N % 8);    
70         N = N / 8;
71     }
72     while (!StackEmpty(&S))
73     {
74         Pop(&S,&e);
75         printf("%d",e);
76     }
77     printf("\n");
78 }
79 
80 void main(void)
81 {
82     conversion();
83 }

 

 

posted on 2012-04-28 14:06  QLinux  阅读(380)  评论(0编辑  收藏  举报

导航