數(shù)據(jù)結(jié)構(gòu)


數(shù)制的轉(zhuǎn)換
【算法步驟】
① 初始化一個空棧S。
② 當(dāng)十進(jìn)制數(shù)N非零時,循環(huán)執(zhí)行以下操作:
把N與8求余得到的八進(jìn)制數(shù)壓入棧S;
N更新為N與8的商。
③ 當(dāng)棧S非空時,循環(huán)執(zhí)行以下操作:
彈出棧頂元素e;
輸出e。
【算法描述】
void conversion(int N)
{//對于任意一個非負(fù)十進(jìn)制數(shù),打印輸出與其等值的八進(jìn)制數(shù)
? ?InitStack(S); //初始化空棧S
? ?while(N) {//當(dāng)N非零時,循環(huán)
Push(S,N%8); //把N與8求余得到的八進(jìn)制數(shù)壓入棧S
? ? ? ?N=N/8; //N更新為N與8的商
? ?}
? ?while(!StackEmpty(S))//當(dāng)棧S非空時,循環(huán)
? ?{
? ? ? Pop(S,e); //彈出棧頂元素e
? ? ? cout<<e; //輸出e
? ?}
}
參考代碼:
/***鏈棧實(shí)現(xiàn)數(shù)制的轉(zhuǎn)換***/
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct SNode {
int data;
struct SNode *next;
} SNode, *LinkStack;
Status InitStack(LinkStack &S) {
S = NULL;
return OK;
}
bool StackEmpty(LinkStack S) {
if (!S)
return true;
return false;
}
Status Push(LinkStack &S, int e) {
LinkStack p;
p = new SNode;
if (!p) {
return OVERFLOW;
}
p->data = e;
p->next = S;
S = p;
return OK;
}
Status Pop(LinkStack &S, int &e) {
LinkStack p;
if (!S)
return ERROR;
e = S->data;
p = S;
S = S->next;
delete p;
return OK;
}
//算法3.20 數(shù)制的轉(zhuǎn)換(鏈棧實(shí)現(xiàn))
void conversion(int N) {//對于任意一個非負(fù)十進(jìn)制數(shù),打印輸出與其等值的八進(jìn)制數(shù)
int e;
LinkStack S;
InitStack(S); //初始化空棧S
while (N) //當(dāng)N非零時,循環(huán)
{
Push(S, N % 8); //把N與8求余得到的八進(jìn)制數(shù)壓入棧S
N = N / 8; //N更新為N與8的商
}
while (!StackEmpty(S)) //當(dāng)棧S非空時,循環(huán)
{
Pop(S, e); //彈出棧頂元素e
cout << e; //輸出e
}
}
int main() {//對于輸入的任意一個非負(fù)十進(jìn)制數(shù),打印輸出與其等值的八進(jìn)制數(shù)
int n, e;
cout << "輸入一個非負(fù)十進(jìn)制數(shù):" << endl;
cin >> n;
conversion(n);
return 0;
}

