利用栈的基本操作,设计一个算法将一个十进制整数转换成十六进制输出

2024-11-15 23:38:17
推荐回答(1个)
回答1:

/* 栈的链接存储----任意进制转换*/
#include
#include

typedef int ElemType;
struct SNode {
ElemType data;
SNode* next;
};

void InitStack(SNode*& HS)
{
HS = NULL;
}

// 压栈 插入元素
void Push(SNode*& HS, const ElemType& item)
{

SNode* newptr = new SNode; /* 获取动态结点*/
newptr->data = item; /*给新分配的结点赋值*/
newptr->next = HS; /* 向栈顶压入新结点*/
HS = newptr;
}

//从栈中删除一个元素并返回该元素
ElemType Pop(SNode*& HS)
{
if(HS==NULL)
{
cerr<<"无法从空栈中删除元素,退出运行 !"< exit(1);
}
SNode* p = HS;
HS = HS->next;
ElemType temp = p->data;
delete p;
return temp;
}

//读取栈顶元素
ElemType Peek(SNode* HS)
{
if(HS==NULL)
{
cerr<<"无法从空链栈中读取元素,退出运行 !"< exit(1);
}
return HS->data;
}

bool EmptyStack(SNode* HS)
{
return HS == NULL;
}

void ClearStack(SNode*& HS)
{
SNode *mp, *np;
mp = HS;
while(mp!=NULL)
{
np = mp->next;
delete mp;
mp = np;
}
HS = NULL;
}

void Transform(long number, int r)
{
SNode *a;
InitStack(a);
while(number!=0)
{
int k = number%r;
Push(a,k);
number = number/r;
}
while(!EmptyStack(a))
{
if(r!=16) cout< else
{
int x = Pop(a);
if(x<10) cout< else
{
switch(x)
{
case 10: cout<<'A'; break;
case 11: cout<<'B'; break;
case 12: cout<<'C'; break;
case 13: cout<<'D'; break;
case 14: cout<<'E'; break;
case 15: cout<<'F'; break;
}
}
}
}
cout<}

void main()
{

cout<<"请输入一个长整数(最长十位有效数字): ";
long n;
cin>>n;
cout<<"长整数 "< Transform(n,16);

cout<<"长整数 "< Transform(n,10);

cout<<"长整数 "< Transform(n,8);

cout<<"长整数 "< Transform(n,6);

cout<<"长整数 "< Transform(n,4);

cout<<"长整数 "< Transform(n,2);
}