1. 程式人生 > >C++ 棧-漢諾塔

C++ 棧-漢諾塔

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

template <typename T>
struct ChainNode
{
	// 資料成員
	T elem;
	ChainNode<T> *next;
	ChainNode(ChainNode<T> *ptr = NULL){ next = ptr; }   // 不能用new,不是一個完整的型別
	ChainNode(const T& elem, ChainNode<T> *ptr = NULL){
		this->elem = elem;
		next = ptr;
	}
};

class MyException{
private:
	string mesg;
public:
	MyException(const char *str) :mesg(const_cast<char*>(str)){  }
	const char* what(){ return mesg.c_str(); }
};

// 棧基類
template <typename T>
class Stack{
public:
	virtual void push(const T&) = 0;
	virtual void pop() = 0;
	virtual int size() const = 0;
	virtual bool empty() const = 0;
	virtual T top() = 0;
};

// 鏈棧
template <typename T>
class linkStack :public Stack<T>
{
private:
	ChainNode<T>* topStack;
	int stackSize;
public:
	string name;
	linkStack(const char *str=""):name(const_cast<char*>(str)){
		stackSize = 0;
		topStack = NULL;
	}
	~linkStack(){
		while (topStack != NULL){
			ChainNode<T>* tmp = topStack;
			topStack = topStack->next;
			delete[] tmp;
		}
	}
	bool empty() const{
		if (stackSize <= 0) return 1;
		return 0;
	}
	int size()const{ return stackSize; }
	void ShowAll(){
		while (!empty()){
			cout << topStack->elem << ' ';
			pop();
		}
		cout << endl;
	}
	void push(const T& data){
		ChainNode<T>* newNode = new ChainNode<T>;
		newNode->elem = data;
		newNode->next = topStack;
		topStack = newNode;
		stackSize++;
	}
	void pop(){
		if (stackSize <= 0){
			throw MyException("Stack empty!");
		}
		
		ChainNode<T>* tmp = topStack;
		topStack = topStack->next;
		delete[] tmp;
		stackSize--;
	}
	T top(){
		if (stackSize <= 0){
			throw MyException("Stack empty!");
		}
		return topStack->elem;
	}
};

template <typename T>
void Hanio(int n,linkStack<T> &poleX, linkStack<T> &poleY, linkStack<T> &poleZ){
	if (n == 1){
		poleZ.push(poleX.top());
		poleX.pop();
		cout << poleX.name << "-->"<<poleZ.name << endl;
	}
	else{
		Hanio(n-1,poleX, poleZ, poleY);
		poleZ.push(poleX.top());
		poleX.pop();
		cout << poleX.name << "-->"<<poleZ.name << endl;
		Hanio(n-1,poleY, poleX, poleZ);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	linkStack<int> StackA("A"),StackB("B"),StackC("C");
	for (int i =4; i > 0; i--) 	StackA.push(i);

	Hanio(StackA.size(),StackA, StackB, StackC);
	
	StackC.ShowAll();
	return 0;
}
<img src="https://img-blog.csdn.net/20160620222619536?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />