//严蔚敏《数据结构》
//栈的应用举例:数制转换(十进制->其他d进制),在此我采用链栈的实际应用角度(P37)
//自学数据结构中,加油!!!
#include<iostream>
using namespace std;
#define ElemType int
typedef struct SNode
{
ElemType data;
struct SNode* prior,* next;
}SNode,* Link;
typedef struct
{
Link head,tail;
int len;
}LinkStack;
bool Init_Stack(LinkStack& s)//初始化链栈
{
s.head=new SNode;
if(!s.head)
return false;
s.head->next=s.head->prior=nullptr;
s.tail=s.head;
s.len=0;
return true;
}
void Output_Stack(LinkStack s)//遍历输出链栈元素
{
Link p=s.tail;//p从栈顶开始遍历
cout<<"栈元素:(从栈顶开始遍历)\n";
cout<<"--------"<<endl;
while(p){
cout<<p->data<<endl;
p=p->prior;
}
cout<<"--------"<<endl;
}
bool IsEmpty_Stack(LinkStack s)//链栈为空,返回true;否则返回false
{
if(!s.len)
return true;
return false;
}
bool Push_Stack(LinkStack& s,ElemType e)//入栈
{
Link p=new SNode;
if(!p)
return false;
p->data=e;
p->next=s.tail->next;
s.tail->next=p;
p->prior=s.tail;
s.tail=p;
s.len++;
return true;
}
bool Pop_Stack(LinkStack& s,ElemType& e)//出栈
{
Link p=s.tail->prior;
e=s.tail->data;
free(s.tail);
s.tail=p;
s.len--;
return true;
}
void Conversion()//进制转换(10->d)函数(自带 栈 与 数据的输入)
{
LinkStack s;
Init_Stack(s);
ElemType num;
cout<<"输入一个十进制整数:";
cin>>num;
int d;
cout<<"输入转换的进制:";
cin>>d;
while(num){
Push_Stack(s,num%d);
num/=d;
}
cout<<"转换为:";
int e;
while(!IsEmpty_Stack(s)){
Pop_Stack(s,e);
cout<<e;
}
cout<<endl;
}
int main()
{
Conversion();
return 0;
}
输入一个十进制整数:1348
输入转换的进制:8
转换为:2504
Process returned 0 (0x0) execution time : 4.421 s
Press any key to continue.
输入一个十进制整数:1348
输入转换的进制:16
转换为:544
Process returned 0 (0x0) execution time : 5.007 s
Press any key to continue.