C++用顺序栈实现进制转换

C++语言,用顺序栈实现十进制向任意进制的转换
#include<iostream>
#include<stdlib.h>
#include<fstream>
using namespace std;
typedef int ElemType;

struct Stack{
	ElemType *stack;
	int top;
	int MaxSize;
};

//1初始化栈S为空 
void InitStack(Stack& S){
	S.MaxSize=10;
	S.stack=new ElemType[S.MaxSize];
	if(!S.stack){
		cerr<<"动态存储空间分配失败!"<<endl;
		exit(1);
	}
	S.top=-1;
}
//元素item入栈,插入到栈顶
void Push(Stack& S,ElemType item){
	if(S.top==S.MaxSize-1){
		int k=sizeof(ElemType);
		S.stack=(ElemType*)realloc(S.stack,2*S.MaxSize*k);
		S.MaxSize=2*S.MaxSize;
	}
	//栈顶指针后移一个位置 
	S.top++;
    //将新元素插入到栈顶
	S.stack[S.top]=item; 
} 

//2删除栈顶元素并返回
ElemType Pop(Stack& S){\
// 若栈顶为空,则退出运行
     if(S.top==-1){
     	cerr<<"Stack is empty!"<<endl;
     	exit(1);
	 } 
	 S.top--;
	 return S.stack[S.top+1]; 
} 

//4、读取栈顶元素的值
ElemType Peek(Stack& S){
	if(S.top==-1){
     	cerr<<"Stack is empty!"<<endl;
     	exit(1);
	 } 
	 
	 return S.stack[S.top]; 
}

//5、判断S是否为空,若是返回true
bool EmptyStack(Stack& S){
	return S.top==-1;
} 

//6、清除栈中所有的元素,释放动态存贮空间
void ClearStack(Stack& S){
	if(S.stack){
		delete []S.stack;
		S.stack=0;
	}
	S.top=-1;
	S.MaxSize=0;
} 

main(){
	Stack s;
	InitStack(s);
	int n,b;
	cout<<" 请输入待转换的十进制数:"<<endl; 
	cin>>n;
	cout<<" 请输入转换的进制:"<<endl; 
	cin>>b; 
	while(n){
		int i=n%b;
		Push(s,i);
	    n=n/b;
	}
	cout<<"转换结果为:"; 
	while(!EmptyStack(s)){
		cout<<Pop(s);	
	}
	cout<<endl;	
	cout<<endl;
	cout<<endl;
	while(1)
	main(); 	 	
}
运行结果

在这里插入图片描述

  • 20
    点赞
  • 135
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值