接leetcode ques1,图的存储与copy代码

邻接表vector存储头节点,不改变struct结构

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<string.h>
#include<cstdarg>
using namespace std;
#define LISTNUM 3

typedef struct Node
{
	char  data[2];
	int  listLen;
	vector<Node*> vec;

};
//lenA。。。每个节点链表长度
int creatGraph(Node  *&srcNode,Node **&srcInNode, int lenA,...)
{
	string  nodeData;
	srcNode=(Node*)malloc(sizeof(Node));
	srcInNode =(Node**)malloc(sizeof(Node*)*LISTNUM);
	va_list arg_p;
	va_start(arg_p,lenA);
	printf("tolal list number:%d\n",LISTNUM);
	int i=lenA;
		for(int k=0;(k<LISTNUM)&&(i!=-1);k++)
		{
			printf("node list length:%d\n",i);
			srcInNode[k]=(Node*)malloc(sizeof(Node)*i);
			srcNode->vec.push_back(srcInNode[k]);
			for(int j=0;j<i;j++)
			{	
				printf("input node num%d:",j);
				cin >> nodeData;
				strcpy((srcInNode[k]+j)->data,nodeData.c_str());
				(srcInNode[k]+j)->listLen=i;	
			}
			i=va_arg(arg_p,int);
		}
	va_end(arg_p);
	return 0;
}

void printGraph(Node * &node)
{
	for(std::vector<Node*>::iterator p=node->vec.begin();!((node->vec).empty())&&(p!=node->vec.end());p++)
	{
			for(int i=0;i<(*p)->listLen-1;(*p)++,i++)
			{
				printf("%s->",(*p)->data);
			}
			printf("%s\n",(*p)->data);
	}
}
int copyGraph(Node *&desNode,Node *&srcNode,Node **©InNode)
{		
	int j=0;
	int len;
	desNode = (Node *)malloc(sizeof(Node));
	copyInNode = (Node **)malloc(sizeof(Node *)*LISTNUM);
	std::vector<Node*>::iterator p;
	for( p=srcNode->vec.begin();!((srcNode->vec).empty())&&(p!=srcNode->vec.end());p++)
	{
		len = (*p)->listLen;	
		copyInNode[j] = (Node*) malloc(sizeof(Node)*(len));
		desNode->vec.push_back(copyInNode[j]);
		j++;
		for(int i=0;i<len;i++)
		{
			strcpy((copyInNode[j]+i)->data,(*p+i)->data);
			(copyInNode[j]+i)->listLen = len;
		}		
	}
	return 0;
}
void cFree(Node *&node,Node *©Node,Node **&inNodeList,Node **©inNodeList)
{
	free(node);
	free(copyNode);
	for(int i=0;i<LISTNUM;i++)
	{
		free(inNodeList[i]);
		free(copyinNodeList[i]);		
	}
	free(inNodeList);
	free(copyinNodeList);
}
int main()
{
	Node *node;
	Node *copyNode;
	Node **inNodeList;
	Node **copyinNodeList;

	//example:orginal graph (A,B)(B,A,C)(C,B)
	creatGraph(node,inNodeList,2,3,2,-1);
	printGraph(node);
	copyGraph(node,copyNode,copyinNodeList);
	printGraph(copyNode);
	cFree(node,copyNode,inNodeList,copyinNodeList);
	return 0;		
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值