//案例分析:将一个十进制数N转化为八进制数,在计算过程中,使得N模8得到八进制数的各个数依次进栈,
//然后将八进制数依次输出,得到八进制数。
#include<iostream>
#include<cstdlib>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define MAXSIZE 100
typedef int Elemtype;
typedef int Status;
//顺序栈实现
typedef struct
{
Elemtype* base;
Elemtype* top;
int stacksize;
}Sqstack;
Status Initstack(Sqstack& s);//初始化顺序栈
Status Insertstack(Sqstack& s, int x);//向顺序栈中插入元素
Status Printstack(Sqstack s);//输出顺序栈
int main(void)
{
int num = 0;
cout << "输入十进制数字num:";
cin >> num;
Sqstack s;
Initstack(s);
while(num){
Insertstack(s, num % 8);
num = num / 8;//更新十进制数字,除以8之后的商
}
cout << "\n输出转化的八进制数为:";
Printstack(s);
return OK;
}
Status Initstack(Sqstack& s)
{
s.base = new Elemtype[MAXSIZE];//为顺序栈动态分配一个最大容量为MAXSIZE的数组空间
if (!s.base) exit(OVERFLOW);//存储分配失败
s.top = s.base;//top初始化为base,空栈
s.stacksize = MAXSIZE;//栈的最大容量为MXAXSIZE
return OK;
}
Status Insertstack(Sqstack& s, int x)
{
if (s.top - s.base == s.stacksize) return ERROR;//判断栈是否满
*(s.top) = x;
s.top++;
return OK;
}
Status Printstack(Sqstack s)
{
if (s.base == s.top) return ERROR;//空栈
for (int k = 0; k < s.top - s.base; k++)
{
cout << *(s.top - k - 1);
}
cout << endl;
return OK;
}
//链栈实现
typedef struct SNode
{
Elemtype data;
struct SNode* next;
}SNode, * Linklist;
Status InitStack(Linklist& S);//初始化链栈
Status PushStack(Linklist& S, Elemtype e);//入链栈
Status PrintStack(Linklist S);//逆序打印链栈
int main(void)
{
int num = 0;
cout << "输入十进制数字num:";
cin >> num;
Linklist S;
S = NULL;
InitStack(S);
while (num) {
PushStack(S, num % 8);
num = num / 8;//更新十进制数字,除以8之后的商
}
cout << "\n输出转化的八进制数为:";
PrintStack(S);
return OK;
}
Status InitStack(Linklist& S)//初始化链栈
{
S = NULL;
return OK;
}
Status PushStack(Linklist& S, Elemtype e)//入链栈
{
SNode* p;
p = new SNode;
p->data = e;
p->next = S;
S = p;
return OK;
}
Status PrintStack(Linklist S)//逆序打印链栈
{
if (S == NULL)
{
cout << "链栈为空。" << endl;
}
cout << "链栈中的元素有:";
SNode* p;
p = S;
while (p != NULL)
{
cout << p->data;
p = p->next;
}
return OK;
}