#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);
}
为什么在转换中不用数组:栈的引入简化了程序设计的问题,划分了不同的关注层次,使思考范围减小了;
而数组不仅掩盖了问题的本质,还要分散精力去考虑数组下标增减的细节问题。