Description 建立顺序栈或链栈,编写程序实现十进制数到二进制数的转换。 Input 输入只有一行,就是十进制整数。 Output 转换后的二进制数。 #include <stdio.h> #include <stdlib.h> typedef struct{ int *base; int *top; int stacksize; }*SqStack,myStack; #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 int InitStack(SqStack s) { s->base=(int*)malloc(STACK_INIT_SIZE*sizeof(int)); if(!s->base) return 0; s->top=s->base; s->stacksize=STACK_INIT_SIZE; return 1; } int Push(SqStack s,int data) { int *newtmp; if(s->top - s->base >=s->stacksize) //栈满 追加存储空间 { newtmp=(int*)realloc(s->base,(s->stacksize+STACKINCREMENT)*sizeof(int)); if(!newtmp)return 0; s->base = newtmp;//函数自动复制之前的数据到新的区域,改变头指针 s->top =s->base+s->stacksize; s->stacksize += STACKINCREMENT; } *(s->top++)=data;//先存储data,然后指针加 return 1; } int Pop(SqStack s) { int e; //空栈, if(s->top == s->base) return 0; //先把指针降下来,然后取出数据 e = *(--s->top); return e; } int GetTop(SqStack s) { int e; if(s->top == s->base) return 0; e = *(s->top-1); return e; } int StackEmpty(SqStack s) { if(s->base == s->top) return 1; else return 0; } void conversion(SqStack s) { int N,b=2; int e; //scanf("%d %d",&N,&b); scanf("%d",&N); while(b>1 && N>0) { Push(s,N%b); N = N/b; } while(!StackEmpty(s)) { e = Pop(s); if(e<=9) printf("%d",e); else printf("%c",e-10+'A'); } } int Mach(myStack *s) { char ch; int e; while( (ch=getchar())!='#') { switch(ch) { case '(': Push(s,ch); break; case ')': if(StackEmpty(s)||GetTop(s)!='(') { printf("() is not right!\n"); return 0; } else { Pop(s); break; } case '[': Push(s,ch); break; break; case ']': if(StackEmpty(s)||GetTop(s)!='[') { printf("[] is not right!\n"); return 0; } else { Pop(s); break; } }//switch }//while if(StackEmpty(s)) { printf("括号配对对\n"); return 1; } else { printf("括号配对不对\n"); return 0; } } void main() { myStack *s; s=(SqStack)malloc(sizeof(myStack)); InitStack(s); //Mach(s); conversion(s); } <script type="text/javascript" id="wumiiRelatedItems"> </script> 转发至微博 转发至微博