桟十先入后出,而进制之间的转换 , %之后取余数,前面获得余数 位低位,后面的为高位 ,所以可以利用数据结构中的桟。这里是看书后得到的算法,分享给大家。桟没有用STL中的桟。
/** SqStack.h** Created on: 2014-9-15* Author: sfe1012*/#ifndef SQSTACK_H_
#define SQSTACK_H_
#include"AStack.h"
#include <assert.h>
template<typename T>
class SqStack : public AStack<T>
{
private:T *m_Base , *m_Top;int m_iStackSize;
public:
SqStack(const int & iSize = 1)
{m_Base = new T[iSize];assert(m_Base != NULL); // 预言 空间分配失败 退出m_Top = m_Base;m_iStackSize = iSize;
}
~SqStack()
{delete []m_Base;
}
void ClearStack()
{m_Top = m_Base;
}
bool StackEmpty()const
{return m_Top == m_Base;
}
int StackLength()const
{return m_Top - m_Base;
}
bool GetTop(T &e)const
{if(m_Top > m_Base){e = *(m_Top -1);return true;}elsereturn false;
}
bool Push(const T&e)
{T *NewBase;if( (m_Top - m_Base) == m_iStackSize ){NewBase = new T[m_iStackSize *2];if(NewBase == NULL)return false;for(int i =0 ; i < m_iStackSize; i++ ){*(NewBase + i ) = *( m_Base + i);}delete []m_Base;m_Base = NewBase;m_Top = m_Base + m_iStackSize;m_iStackSize *= 2;}*m_Top ++ = e;return true;
}
bool Pop(T &e)
{if(m_Top == m_Base){return false;}e = *( --m_Top );return true;
}
void StackTraverse(void(*Visit)(T *))const
{T *p = m_Base;while(p < m_Top)Visit(p++);std::cout<<std::endl;
}
};
#endif /* SQSTACK_H_ */
/** TenToX.h** Created on: 2014-9-15* Author: sfe1012*/#ifndef TENTOX_H_
#define TENTOX_H_
#include"SqStack.h"
#include<iostream>
const char IntToChar[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
void Conversion(const int &iTen , const int & iX)
{int iTenTemp = iTen;SqStack<int> oSqStack(5);if(iTen >= 0 && iX >=2 && iX <=16 ){while(iTenTemp){oSqStack.Push(iTenTemp % iX);iTenTemp = iTenTemp / iX ;}}int iSqStackSize = oSqStack.StackLength();char * StackBuffer = new char[iSqStackSize + 1];int iE;int i = 0;while(!oSqStack.StackEmpty()){oSqStack.Pop(iE);StackBuffer[i++] = IntToChar[iE];}StackBuffer[i] = '\0';std::string strStack(StackBuffer);delete[]StackBuffer;std::cout<<"After Turn :" << strStack<<std::endl;
}#endif /* TENTOX_H_ */