【图的深拷贝 | 递归销毁 Graph:DeepCopy | RecurringDetor】

#include 
#include 
template < typename Value >
class Graph{
struct Node{
	Value  val;
	std::vector< Node * > neighbors;
};
public:
	Node *interaface { nullptr };
	Graph( void ) noexcept = default;
	Graph( Graph&& other ) noexcept
		: interaface( other.interface )
	{
		other.interaface = nullptr;
	};
	
	explicit Graph( const Graph& other ) {
		std::unordered_map< Node *, Node * > hash;
		interaface->neighbors.swap(
			__DeepCopyConstructHelper(
				&const_cast< Node& >
				( other.interaface ), hash)
				->neighbors );
	}
	~Graph( void ){
		__RecursivetDestructHelper( this );
	}
private:
	Node *__DeepCopyConstructHelper( Node *o,
		std::unordered_map< Node *, Node * > &hash)
	{
		if( !o ) return nullptr;
		if( hash.count( o ) ) return hash[o];
		Node *_Clone { new Node( *o ) };
		hash.insert( { o, _Clone } );
		auto& ONeighbors = o->neighbors;
		auto& CNeighbors = _Clone->neighbors;
		for( auto& _W : ONeighbors )
			CNeighbors.emplace_back( __DeepCopyConstructHelper( _W, hash ) );
		return _Clone;
	}
	
	void __RecursivetDestructHelper( Node *o ){
		if( !o ) return;
		auto& neighbors = o->neighbors;
		for( auto& _W : neighbors )
			__RecursivetDestructHelper( _W );
		delete o;
		o = nullptr;
	}
};


你可能感兴趣的:(ADT数据结构实现,算法,哈希算法,算法,图论,数据结构,c++)