数据结构--栈应用1:将十进制整数转换成二至九任意进制(C++实现)

思路:利用短除法求解,短除法的具体思路这里不做介绍。
原因:在整数的进制转化时,利用短除法,先得到的余数最后输出,这样就可以将先得到的余数入栈,等短除结束在反向输出,即为答案。这里只限于整数,对小数的短除输出顺序是正序,这里不做介绍。
代码:分成三个文件,见下面。
1.Node.h文件,这个文件主要是生成结点,为了方便函数的实现写在了.h文件中。

template class Stack;
template
class Node
{
	friend class Stack;
public:
	//用默认构造函数给头结点的指针域清空
	Node()
	{
		this->next = NULL;
	}
	//用一般构造函数给一般结点赋值
	explicit Node(T data)
	{
		this->data = data;
		this->next = NULL;
	}
private:
	T data;
	Node *next;
};

2.Stack.h文件, 这个文件主要是建立栈,并对栈进行操作,这里只实现部分需要的函数。
注:代码中使用了try…catch语法,是想尝试下这个语法的使用,博主也是第一次接触到这种使用方法。

#include "Node.h"

template
class Stack
{
public:
	//构造一个头结点
	Stack()
	{
		this->head = new Node;
		this->top = this->head->next;
	}
	////生成一般结点
	//Stack(T data)
	//{
	//	this->top = new Node;
	//	this->top->next = this->head->next;
	//	this->head->next = this->top;
	//}
	void show()const
	{
		if (this->top == NULL)
		{
			cout << "空栈!" << endl;
			return;
		}
		Node *p = this->top;
		while (p != NULL)
		{
			cout << p->data << " ";
			p = p->next;
		}
		cout << endl;
		return;
	}
	Stack& push(const T& data)
	{
		this->top = new Node(data);
		this->top->next = this->head->next;
		this->head->next = this->top;
		return *this;
	}
	T pop(){
		try{
			if (this->top == NULL){
				throw false;
			}
			Node *p = this->top;
			T data = p->data;
			this->top = this->top->next;
			this->head->next = this->top;
			delete p;
			return data;
		}
		catch(bool){
			cout << "pop error, stack is empty!" << endl;
			exit(-1);
		}
	}
private:
	Node *head;
	Node *top;
};

3.主函数

#include "stdafx.h"
#include 
#include "Stack.h"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	int x;
	int n;
	cout << "输入转换值:";
	cin >> x;
	cout << endl <<"输入转换后的进制:";
	cin >> n;
	int temp = x;
	//int y;
	Stack cache;

	while (temp >= n)
	{
		cache.push(temp%n);
		temp = int(temp / n);
	}
	cache.push(temp);
	cache.show();
	while (1);
	return 0;
}

因为前几天电脑出了问题,保存在电脑里链表那部分练习全部没有了,伤心!现在开始同步到博客上来。如果有不足之处,欢迎指正!

你可能感兴趣的:(数据结构--栈应用1:将十进制整数转换成二至九任意进制(C++实现))