C语言栈的实现进制转换

来源:互联网 发布:以利天诚大数据 编辑:程序博客网 时间:2024/04/30 15:12
栈是限定仅在表尾进行操作的线性表。因此,对栈来说,表尾端有其特殊含义,成为栈顶,相应地,表头端称为栈底。下面用C实现栈的基本操作以及利用栈来实现一个进制转换程序
#include <iostream>#include <stdio.h>#include <stdlib.h>using namespace std;#define STACK_INIT_SIZE 100#define STACKINCREMENT 10typedef int SElemType;typedef struct{    SElemType * base;    SElemType * top;    int stacksize;}SqStack;int InitStack(SqStack &S){    S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));    if(!S.base) return 0;    S.top = S.base ;    S.stacksize = STACK_INIT_SIZE;    return 1;}//添加栈元素int Push(SqStack &S,SElemType e){    if(S.top-S.base >= S.stacksize)    {        S.base = (SElemType * )realloc(S.base,(S.stacksize+STACK_INIT_SIZE)*sizeof(SElemType));        if(!S.base) return 0;        S.top = S.base + S.stacksize;        S.stacksize += STACK_INIT_SIZE;    }    * S.top = e;    S.top ++ ;    return 1;}int Pop(SqStack &S,SElemType &e){    if(S.top<=S.base) return -1;    e = * --S.top;    return 1;}int GetTop(SqStack S,SElemType &e){    if(S.top<=S.base) return -1;    e = * (S.top-1);    return 1;}int StackEmpty(SqStack S){    if(S.base == S.top)        return 1;    else        return 0;}int main(){    cout << "进制转换程序" << endl;    SqStack S;    InitStack(S);    int n,m;    cout << "请输入一个整数" << endl;    scanf("%d",&n);    cout << "请输入进制,用整数表示" << endl;    scanf("%d",&m);    while(n)    {        Push(S,n%m);        n = n/m;    }    int e;    while(!StackEmpty(S))    {        Pop(S,e);        printf("%d",e);    }    return 0;}

测试结果:
这里写图片描述

0 0
原创粉丝点击