栈的基本实现

来源:互联网 发布:淘宝购买基金 编辑:程序博客网 时间:2024/05/12 06:26
#include<iostream>#include<malloc.h>using namespace std;const stackSize = 10;const stackIncrement = 5;typedef struct{int *base;int *top;int stackSize;} SqStack;int InitStack(SqStack &s){s.base = (int*)malloc( stackSize*sizeof(int) );if(!s.base)return 0;s.top = s.base;s.stackSize = stackSize;return 1;}int Push(SqStack &s, int e){if(s.top - s.base >= s.stackSize){s.base = (int*)realloc(s.base, (s.stackSize + stackIncrement)*sizeof(int) );if(!s.base)return 0;s.top = s.base + s.stackSize;s.stackSize += stackIncrement;}*s.top++ = e;return 1;}int Pop(SqStack &s, int &e){if(s.top == s.base)return 0;e = *(--s.top);return 0;}int StackEmpty(SqStack s){if(s.top == s.base)return 0;return 1;}int StackLenth(SqStack s){return (s.top - s.base);}int main(){int decimal;cout<<"请输入一个十进制的数: ";cin>>decimal;SqStack stack;InitStack(stack);while(decimal){Push(stack, decimal % 2);decimal /= 2;}cout<<StackLenth(stack)<<"此数转换为二进制后为:"<<endl;int e = 0;while( StackEmpty(stack) != 0 ){Pop(stack, e);cout<<e;}cout<<endl;return 0;}


 

0 0
原创粉丝点击