利用stack实现进制转换
Stack.h
#ifndef _STACK_H_ #define _STACK_H_ #include<iostream> #include<assert.h> using namespace std; typedef int ElemType; #define STACK_MAX_SIZE 100 #define HEX 2 typedef struct Stack { ElemType *base;//栈底指针 int top; //栈顶标识 int stacksize; //当前入栈元素个数 int capacity; //最大容量 }Stack; void InitStack(Stack *stack);//初始化stack bool isfull(Stack *stack);//判断stack是否为满 bool isempty(Stack *stack);//<span style="font-size: 12.6315793991089px; font-family: Arial, Helvetica, sans-serif;">判断stack是否为空</span> bool push(Stack *stack,ElemType x);//入stack //int pop(Stack *stack); bool show_stack(Stack *stack);//打印 void clear(Stack *stack);//清空 void destroy(Stack *stack);//销毁 void Pop(Stack *stack,ElemType *e);//弹stack,并返回stack顶元素 #endif //_STACK_H_
<span style="font-family:Arial, Helvetica, sans-serif;font-size:24px;color:#ff0000;">stack.cpp</span>
<pre name="code" class="cpp">#include"Stack.h" void InitStack(Stack *stack) { stack->base = (ElemType *)malloc(sizeof(ElemType)*STACK_MAX_SIZE); assert(stack->base != NULL); stack->top = 0; stack->capacity = STACK_MAX_SIZE; stack->stacksize = 0; } bool isfull(Stack *stack) { return stack->stacksize == stack->capacity; } bool isempty(Stack *stack) { return stack->stacksize == 0; } bool push(Stack *stack,ElemType x) { if(isfull(stack)) return false; stack->base[stack->top++] = x; stack->stacksize++; return true; } void Pop(Stack *st,ElemType *e) { if(isempty(st)) { cout<<"栈以空,不能出栈!"<<endl; } --(st->top); *e = st->base[st->top]; st->stacksize--; } /* bool pop(Stack *stack) { if(isempty(stack)) return false; stack->base[stack->top--]; return true; }*/ ElemType GetTop(Stack *stack,ElemType *x) { if(isempty(stack)) { cout<<"栈空!"<<endl; } return stack->base[stack->stacksize-1]; } bool show_stack(Stack *stack) { if(isempty(stack)) return false; for(int i = stack->top-1;i>=0;--i) cout<<stack->base[i]<<endl; return true; } void clear(Stack *stack) { stack->top = 0; } void destroy(Stack *stack) { clear(stack); free(stack->base); stack->capacity = 0; stack->stacksize = 0; }
main.cpp
#include"Stack.h" void conversion(int n) { Stack mystack; int m; InitStack(&mystack); while(n) { push(&mystack,n%HEX); n = n / HEX; } while(!isempty(&mystack)) { // show_stack(&mystack); // mystack.top = 0; Pop(&mystack,&m); cout<<m; } cout<<endl; } void main() { int n = 25555; cout<<n<<" conversion "<<HEX<<" hex is "; conversion(n); }
时间: 2024-11-05 04:39:20