利用棧實現進制的轉換

其實平時處理進制轉換的處理方式更方便,最後只需處理一下倒序輸入就可以了!
然而爲了體現棧“後進先出” 的思想,利用棧來處理最後結果的倒序輸出囧。


#include <iostream>
#include <stdio.h>
#include <algorithm>

#define ERROR 0
#define OK 1
#define OVERFLOW -1
#define STACK_INIT_SIZE 100//棧的大小
#define STACKINCREMENT 10
using namespace std;


typedef struct
{
int * base;//在棧構造以前和銷燬之後,base的值爲null
int * top;//棧頂指針
int stacksize;//當前已分配的存儲空間,以元素爲單位
}SqStack;


int InitStack(SqStack & S)//構造一個空棧S
{
S.base = (int*)malloc(STACK_INIT_SIZE* sizeof(int));
if(!S.base)
exit(OVERFLOW);//存儲分配失敗
S.top=S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}


bool StackEmpty(SqStack S)
{
if(S.base == S.top)
return true;
return false;


}


int Push(SqStack &S, int e)//插入元素e爲新的棧頂元素
{
if(S.top - S.base >= S.stacksize)//棧滿了,追加空間
{
S.base = (int *)realloc (S.base,(S.stacksize + STACKINCREMENT)*sizeof(int));
if(!S.base)//存儲分配失敗
exit(ERROR);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top ++ = e;
return OK;
}


int Pop(SqStack & S, int &e)//若棧不爲空,則刪除S的棧頂元素,用e返回其值,返回OK否則返回ERROR
{
if(S.top == S.base)//空棧
return ERROR;


e = *--S.top;
return OK;
}


int main()
{


SqStack S;
int e;
int n;
InitStack(S);
cout<<"輸入進制的數字:"<<endl;
cin>>n;
if(n<0)
{
cout<<"請輸入正整數"<<endl;
return 0 ;
}
if(!n)
Push(S,0);
while(n)//進制轉換處理
{
Push(S,n%8);
n=n/8;
}
cout<<"結果是"<<endl;
while(!StackEmpty(S))//倒序輸出,即出棧
{
Pop(S,e);
cout<<e;
}
return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章