【数据结构之栈】十进制转其他进制--栈基本操作

最近新学习到了栈,对于栈的理解比较浅显,这里说一下栈的基本操作,用了进制转换的例子:

以十进制为例子,例如:
(1348)10=(2504)8

运算过程:
N              N div 8         N mod 8

1348         168              4

168           21                0

21             2                 5

2               0                 2

 

下面是代码部分:

1.定义栈

typedef struct 
{
    int *top;
    int *base;
    int stacksize;
}SqStack;

2.初始化栈

//Initiate the stack
int InitStack(SqStack &S)
{
    S.base=(int *)malloc(STACK_INIT_SIZE*sizeof(int));
    if (!S.base)
        exit(-1);
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;

    return 1;
}

3.压栈

//Push an element into the stack
int Push(SqStack &S,int e)
{
    if (S.top-S.base>=STACK_INIT_SIZE)        //if the stack is full
    {
        S.base=(int *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(int));
        if (!S.base)
            return -1;
        S.top=S.base+S.stacksize;
        S.stacksize+=STACKINCREMENT;
    }                
    *(++S.top)=e;

    return 1;
}

4.出栈

//Pop an element from the stack
int Pop(SqStack &S,int &e)
{
    if (S.top!=S.base)
        e=*S.top;
        S.top--;
    return 1;
}

5.获取栈顶元素

//Get the top of the stack
int GetTop(SqStack S,int &e)
{
    if (S.top!=S.base)
        e=*S.top;
    return 1;
}

6.进制转换

void conversion(int num,int size)
{
    int e;
    SqStack S;

    InitStack(S);
    while (num)
    {
        Push(S,num%size);
        num/=size;
    }
    

    while (S.top!=S.base)
    {
        Pop(S,e);
        cout<<e;
    }

}

 

 

总结:利用栈的LIFO的特点,恰好能够快速地处理进制转换时倒叙输出的方式,这个例子也能很好地理解栈的特点,学习栈的初始化,栈操作:压栈,出栈,获取栈顶元素等。

posted @ 2016-10-05 15:13  HugoNgai  阅读(906)  评论(0编辑  收藏  举报