数值转换

#include <iostream>
using namespace std;
template <class T>
class node
{
public:
	node<T>* next;
	T val;
	node():next(NULL),val(){};
	node(T v):next(NULL),val(v){};
};
template <class T>
class my_stack
{
public:
	my_stack();
	~my_stack();
	void init_stack();
	bool is_empty();
	size_t get_len();
    T* get_top();
	void push(const T& e);
    void pop(T& e);
	void display();
private:
    node<T>* top;
    size_t len;
};
template <class T>
my_stack<T>::my_stack()
{
   top  = NULL;
   len = 0;
}
template <class T>
my_stack<T>::~my_stack()
{
	node<T>* pre = top;
	if (top)
	{
       delete top;
	   top = pre->next;
	   pre = pre->next;
	}
	len = 0;
}
template <class T>
bool my_stack<T>::is_empty()
{
	return len == 0;
}
template <class T>
size_t my_stack<T>::get_len()
{
	return len;
}
template <class T>
void my_stack<T>::push(const T& e)
{
   node<T>* tmp = new node<T>(e);
   if (top == NULL)
   {
	   top =tmp;
   }
   else
   {
	   tmp->next = top;
	   top = tmp;
   }
   ++len;
}
template <class T>
void my_stack<T>::pop(T& e)
{
	if(is_empty())
		throw new exception("The stack is empty!");
	e = top->val;
    if (len ==1)
    {
		top  = NULL;
    }
	else
	{
        node<T>* tmp = top;
        top = top->next;
		delete tmp;
	}
	--len;
   
}
template <class T>
void my_stack<T>::display()
{
   node<T>* pre = top;
   cout << "The stack is: ";
   while(pre)
   {
	   cout << pre->val << " ";
	   pre = pre->next;
   }
   cout << endl;
}
void conversion(int N,int s)
{
	my_stack<int> sq;
	while (N)
	{
		sq.push(N%s);
		N /= s;
	}
	int e = 0;
	while(!sq.is_empty())
	{
       sq.pop(e);
	   cout << e << " ";
	}
}
int main()
{
  conversion(72,8);
}
为什么在转换中不用数组:栈的引入简化了程序设计的问题,划分了不同的关注层次,使思考范围减小了;
而数组不仅掩盖了问题的本质,还要分散精力去考虑数组下标增减的细节问题。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值