图的深度遍历和广度遍历--邻接链表法


//LinkList.h
#ifndef _LINKLIST_H_
#define _LINKLIST_H_

typedef void LinkList;
typedef struct _tag_LinkListNode LinkListNode;
struct _tag_LinkListNode
{
    LinkListNode* next;
};

LinkList* LinkList_Create();

void LinkList_Destroy(LinkList* list);

void LinkList_Clear(LinkList* list);

int LinkList_Length(LinkList* list);

int LinkList_Insert(LinkList* list, LinkListNode* node, int pos);

LinkListNode* LinkList_Get(LinkList* list, int pos);

LinkListNode* LinkList_Delete(LinkList* list, int pos);

#endif

//LinkList.c 
#include <stdio.h>
#include <malloc.h>
#include "LinkList.h"

typedef struct _tag_LinkList
{
    LinkListNode header;
    int length;
} TLinkList;

LinkList* LinkList_Create() // O(1)
{
    TLinkList* ret = (TLinkList*)malloc(sizeof(TLinkList));
    
    if( ret != NULL )
    {
        ret->length = 0;
        ret->header.next = NULL;
    }
    
    return ret;
}

void LinkList_Destroy(LinkList* list) // O(1)
{
    free(list);
}

void LinkList_Clear(LinkList* list) // O(1)
{
    TLinkList* sList = (TLinkList*)list;
    
    if( sList != NULL )
    {
        sList->length = 0;
        sList->header.next = NULL;
    }
}

int LinkList_Length(LinkList* list) // O(1)
{
    TLinkList* sList = (TLinkList*)list;
    int ret = -1;
    
    if( sList != NULL )
    {
        ret = sList->length;
    }
    
    return ret;
}

int LinkList_Insert(LinkList* list, LinkListNode* node, int pos) // O(n)
{ 
    TLinkList* sList = (TLinkList*)list;
    int ret = (sList != NULL) && (pos >= 0) && (node != NULL);
    int i = 0;
    
    if( ret )
    {
        LinkListNode* current = (LinkListNode*)sList;
        
        for(i=0; (i<pos) && (current->next != NULL); i++)
        {
            current = current->next;
        }
        
        node->next = current->next;
        current->next = node;
        
        sList->length++;
    }
    
    return ret;
}

LinkListNode* LinkList_Get(LinkList* list, int pos) // O(n)
{
    TLinkList* sList = (TLinkList*)list;
    LinkListNode* ret = NULL;
    int i = 0;
    
    if( (sList != NULL) && (0 <= pos) && (pos < sList->length) )
    {
        LinkListNode* current = (LinkListNode*)sList;
        
        for(i=0; i<pos; i++)
        {
            current = current->next;
        }
        
        ret = current->next;
    }
    
    return ret;
}

LinkListNode* LinkList_Delete(LinkList* list, int pos) // O(n)
{
    TLinkList* sList = (TLinkList*)list;
    LinkListNode* ret = NULL;
    int i = 0;
    
    if( (sList != NULL) && (0 <= pos) && (pos < sList->length) )
    {
        LinkListNode* current = (LinkListNode*)sList;
        
        for(i=0; i<pos; i++)
        {
            current = current->next;
        }
        
        ret = current->next;
        current->next = ret->next;
        
        sList->length--;
    }
    
    return ret;
}

//LinkQueue.h
#ifndef _LINKQUEUE_H_
#define _LINKQUEUE_H_

typedef void LinkQueue;

LinkQueue* LinkQueue_Create();

void LinkQueue_Destroy(LinkQueue* queue);

void LinkQueue_Clear(LinkQueue* queue);

int LinkQueue_Append(LinkQueue* queue, void* item);

void* LinkQueue_Retrieve(LinkQueue* queue);

void* LinkQueue_Header(LinkQueue* queue);

int LinkQueue_Length(LinkQueue* queue);

#endif

//LinkQueue.c
#include <malloc.h>
#include <stdio.h>
#include "LinkQueue.h"

typedef struct _tag_LinkQueueNode TLinkQueueNode;
struct _tag_LinkQueueNode
{
    TLinkQueueNode* next;
    void* item;
};

typedef struct _tag_LinkQueue
{
    TLinkQueueNode* front;
    TLinkQueueNode* rear;
    int length;
} TLinkQueue;

LinkQueue* LinkQueue_Create() // O(1)
{
    TLinkQueue* ret = (TLinkQueue*)malloc(sizeof(TLinkQueue));
    
    if( ret != NULL )
    {
        ret->front = NULL;
        ret->rear = NULL;
        ret->length = 0;
    }
    
    return ret;
}

void LinkQueue_Destroy(LinkQueue* queue) // O(n)
{
    LinkQueue_Clear(queue);
    free(queue);
}

void LinkQueue_Clear(LinkQueue* queue) // O(n)
{
    while( LinkQueue_Length(queue) > 0 )
    {
        LinkQueue_Retrieve(queue);
    }
}

int LinkQueue_Append(LinkQueue* queue, void* item) // O(1)
{
    TLinkQueue* sQueue = (TLinkQueue*)queue;
    TLinkQueueNode* node = (TLinkQueueNode*)malloc(sizeof(TLinkQueueNode));
    int ret = (sQueue != NULL ) && (item != NULL) && (node != NULL);
    
    if( ret )
    {
        node->item = item;
        
        if( sQueue->length > 0 )
        {
            sQueue->rear->next = node;
            sQueue->rear = node;
            node->next = NULL;
        }
        else
        {
            sQueue->front = node;
            sQueue->rear = node;
            node->next = NULL;
        }
        
        sQueue->length++;
    }
    
    if( !ret )
    {
        free(node);
    }
    
    return ret;
}

void* LinkQueue_Retrieve(LinkQueue* queue) // O(1)
{
    TLinkQueue* sQueue = (TLinkQueue*)queue;
    TLinkQueueNode* node = NULL;
    void* ret = NULL;
    
    if( (sQueue != NULL) && (sQueue->length > 0) )
    {
        node = sQueue->front;
        
        sQueue->front = node->next;
        
        ret = node->item;
        
        free(node);
        
        sQueue->length--;
        
        if( sQueue->length == 0 )
        {
            sQueue->front = NULL;
            sQueue->rear = NULL;
        }
    }
    
    return ret;
}

void* LinkQueue_Header(LinkQueue* queue) // O(1)
{
    TLinkQueue* sQueue = (TLinkQueue*)queue;
    void* ret = NULL;
    
    if( (sQueue != NULL) && (sQueue->length > 0) )
    {
        ret = sQueue->front->item;
    }
    
    return ret;
}

int LinkQueue_Length(LinkQueue* queue) // O(1)
{
    TLinkQueue* sQueue = (TLinkQueue*)queue;
    int ret = -1;
    
    if( sQueue != NULL )
    {
        ret = sQueue->length;
    }
    
    return ret;
}

//LGraph.h

#ifndef _LGRAPH_H_
#define _LGRAPH_H_

typedef void LGraph;
typedef void LVertex;
typedef void (LGraph_Print)(LVertex*);
typedef void (LGraph_Print)(LVertex*);

LGraph* LGraph_Create(LVertex** v,int n);

void LGraph_Destroy(LGraph* graph);

void LGraph_Clear(LGraph* graph);

int LGraph_AddEdge(LGraph* graph,int v1,int v2,int w); 

int LGraph_RemoveEdge(LGraph* graph,int v1,int v2);

int LGraph_GetEdge(LGraph* graph,int v1,int v2);

int LGraph_TD(LGraph* graph,int v);

int LGraph_VertexCount(LGraph* graph);

int LGraph_EdgeCount(LGraph* graph);

void LGraph_DFS(LGraph* graph,int v,LGraph_Print* pFunc);

void LGraph_BFS(LGraph* graph,int v,LGraph_Print* pFunc);

void LGraph_Display(LGraph* graph,LGraph_Print* pFunc);

#endif

//LGraph.c

#include "LGraph.h"
#include "LinkList.h"
#include <malloc.h>
#include <stdio.h>
#include "LinkQueue.h"

typedef struct _tag_TLGraph
{
	int count;
	LVertex** v;
	LinkList** la;	
} TLGraph;
typedef struct _tag_ListNode
{
	LinkListNode header;
	int v;
	int w;
}TListNode;

static void recursive_dfs(LGraph* graph,int v,int visited[],LGraph_Print* pFunc)
{
	TLGraph* tGraph = (TLGraph*)graph;
	int i = 0;
	pFunc(tGraph->v[v]);
	visited[v] = 1;
	printf(", ");
	
	for(i=0;i<LinkList_Length(tGraph->la[v]);i++)
	{
		TListNode* node = NULL;
		node = (TListNode*)LinkList_Get(tGraph->la[v],i);
		if(!visited[node->v])
		{
			recursive_dfs(tGraph,node->v,visited,pFunc);	
		}		
	}
}
static void bfs(LGraph* graph,int v,int visited[],LGraph_Print* pFunc)
{
	TLGraph* tGraph = (TLGraph*)graph;
	LinkQueue* queue = LinkQueue_Create();
	if(queue!=NULL)
	{
		LinkQueue_Append(queue,tGraph->v+v);  //	graph->v+vÖÐ graph->vÊÇΪÁ˽â¾öµÚ¶þ¸ö²ÎÊý²»Îª0¶ø¼ÓÉϵģ¬µÈÈ¡³öÀ´Ê±ÔÙ¼ôµô 
		visited[v] = 1;
		while(LinkQueue_Length(queue)>0)
		{
			int i = 0;
			v = (LVertex**)LinkQueue_Retrieve(queue) - tGraph->v;
			pFunc(tGraph->v[v]);
			printf(", ");
			for(i=0;i<LinkList_Length(tGraph->la[v]);i++)
			{
				TListNode* node = NULL;
				node = (TListNode*)LinkList_Get(tGraph->la[v],i);
				if(!visited[node->v])
				{
					LinkQueue_Append(queue,tGraph->v+node->v);//	graph->v+vÖÐ graph->vÊÇΪÁ˽â¾öµÚ¶þ¸ö²ÎÊý²»Îª0¶ø¼ÓÉϵģ¬µÈÈ¡³öÀ´Ê±ÔÙ¼ôµô
					visited[node->v] = 1;
				}	
			}	
		}
	}
	LinkQueue_Destroy(queue);
}

LGraph* LGraph_Create(LVertex** v,int n)
{
	TLGraph* ret = NULL;
	int ok = 1;
	if((v!=NULL)&&(n>0))
	{
		ret = (TLGraph*)malloc(sizeof(TLGraph));
		
		if(ret!=NULL)
		{
			ret->count = n;
			ret->v = (LVertex**)calloc(n,sizeof(LVertex*));
			ret->la = (LinkList**)calloc(n,sizeof(LinkList*));
			
			ok = (ret->v!=NULL)&&(ret->la!=NULL);
			if(ok)
			{
				int i = 0;
				for(i=0;i<n;i++)
				{
					ret->v[i] = v[i];	
				}		
				for(i=0;(i<n)&&ok;i++)
				{
					ok = ok && ((ret->la[i] = LinkList_Create()) != NULL);
				}
			}
			if(!ok) // ´´½¨Á´±íʧ°Üʱ
			{
				if(ret->la!=NULL)
				{
					int i = 0;
					for(i=0;i<n;i++)
					{
						LinkList_Destroy(ret->la[i]);	
					}	
				}
				free(ret->la);
				free(ret->v);
				free(ret);
				ret = NULL;	
			} 	
		}
	}
	
	return ret;
}


void LGraph_Destroy(LGraph* graph)
{
	TLGraph* tGraph = (TLGraph*)graph;
	LGraph_Clear(tGraph);
	if(tGraph!=NULL)
	{
		int i = 0;
		for(i=0;i<tGraph->count;i++)
		{
			LinkList_Destroy(tGraph->la[i]);  //Õâ¸öµØ·½£¬ÎÒûÏëµ½ 
		}
		
		free(tGraph->la);
		free(tGraph->v);
		free(tGraph);	
		
	}
}
void LGraph_Clear(LGraph* graph)
{
	TLGraph* tGraph = (TLGraph*)graph;
	if(tGraph!=NULL)
	{
		int i = 0;
		for(i=0;i<tGraph->count;i++)
		{
			while(LinkList_Length(tGraph->la[i]) > 0)
			{
				free(LinkList_Delete(tGraph->la[i],0));  //ºÜ¶ÀÌØż 
			}	
		}	
	}
}
int LGraph_AddEdge(LGraph* graph,int v1,int v2,int w)
{
	int ret = 0;
	TLGraph* tGraph = (TLGraph*)graph;
	TListNode* node = (TListNode*)malloc(sizeof(TListNode)); //ÕâÀï²»ÖªµÀΪʲôҪÉêÇë¿Õ¼ä£¬²»ÉêÇëÒ²ÄܱàÒëͨ¹ý 
	//TListNode* node = NULL; 
	ret = (tGraph!=NULL) && (node!=NULL);
	ret = ret && (v1>=0) && (v1<tGraph->count);
	ret = ret && (v2>=0) && (v2<tGraph->count);
	ret = ret && (w>0);
	if( ret )
	{
		node->v = v2;
		node->w = w;
		LinkList_Insert(tGraph->la[v1],(LinkListNode*)node,0);
	}
	return ret;
}
int LGraph_RemoveEdge(LGraph* graph,int v1,int v2)
{
	int ret = 0;
	TLGraph* tGraph = (TLGraph*)graph;
	if((tGraph!=NULL)&&(v1>=0)&&(v1<tGraph->count)&&(v2>=0)&&(v2<tGraph->count))
	{
		TListNode* node = NULL;   //ÕâÀïΪʲô²»ÉêÇë¿Õ¼ä
		//TListNode* node = (TListNode*)malloc(sizeof(TListNode));   
		int i=0;
		for(i=0;i<LinkList_Length(tGraph->la[v1]);i++)
		{
			node = (TListNode*)LinkList_Get(tGraph->la[v1],i);
			if(node->v == v2)
			{
				ret = node->w;
				
				LinkList_Delete(tGraph->la[v1],i);
				free(node);
				
				break;
			}	
		}	
	}
	return ret;
}

int LGraph_GetEdge(LGraph* graph,int v1,int v2)
{
	TLGraph* tGraph = (TLGraph*)graph;
	int ret = 0;
	if((tGraph!=NULL)&&(v1>=0)&&(v1<tGraph->count)&&(v2>=0)&&(tGraph->count))
	{
		int i = 0;
		TListNode* node = NULL;
		for(i=0;i<LinkList_Length(tGraph->la[v1]);i++)
		{
			//TListNode* node = (TListNode*)malloc(sizeof(TListNode));
			
			node = (TListNode*)LinkList_Get(tGraph->la[v1],i);
			if(node->v == v2)
			{
				ret = node->w;	
				break;
			}	
//			free(node);
//			node = NULL;
		}	
	}
	return ret;
}

int LGraph_TD(LGraph* graph,int v)
{
	int ret = 0;
	TLGraph* tGraph = (TLGraph*)graph;
	if((tGraph!=NULL)&&(v>=0)&&(v<tGraph->count))
	{
		ret = LinkList_Length(tGraph->la[v]);   //³ö¶È
		int i = 0;
		int j = 0;
		
		TListNode* node = NULL;
		
		for(i=0;i<tGraph->count;i++)
		{
			for(j=0;j<LinkList_Length(tGraph->la[i]);j++)
			{
				//TListNode* node = (TListNode*)malloc(sizeof(TListNode));
				
				node = (TListNode*)LinkList_Get(tGraph->la[i],j);	
				if(node->v == v)               //Èë¶È 
				{
					ret++;		
				}
//				free(node);
//				node = NULL;
			}	
		} 
			
	}
	return ret;
}

int LGraph_VertexCount(LGraph* graph)
{
	int ret = 0;
	TLGraph* tGraph = (TLGraph*)graph;
	if(tGraph!=NULL)
	{
		ret = tGraph->count;	
	}
	return ret;
} 

int LGraph_EdgeCount(LGraph* graph)
{
	int ret = 0;
	TLGraph* tGraph = (TLGraph*)graph;
	if(tGraph!=NULL)
	{
		int i = 0;
		for(i=0;i<tGraph->count;i++)
		{
			ret = ret + LinkList_Length(tGraph->la[i]);	
		}	
	}
	return ret;
}
void LGraph_DFS(LGraph* graph,int v,LGraph_Print* pFunc)
{
	TLGraph* tGraph = (TLGraph*)graph;
	
	int condition = 0;
	int* visited = (int*)calloc(tGraph->count,sizeof(int));  //¼Ç¼¶¥µã·ÃÎÊÐÅÏ¢ 
	
	condition = (tGraph!=NULL)&&(pFunc!=NULL);
	condition = condition && (v>=0)&&(v<tGraph->count);
	condition = condition && (visited!=NULL);
	
	if(condition)
	{
		recursive_dfs(tGraph,v,visited,pFunc);
		int i = 0;
		for(i=0;i<tGraph->count;i++)    //´¦Àíδ·ÃÎʵĶ¥µã 
		{
			if(!visited[i])
			{
				recursive_dfs(tGraph,i,visited,pFunc);	
			}		
		}
		printf("\n");		
	}
	free(visited);
}

void LGraph_BFS(LGraph* graph,int v,LGraph_Print* pFunc)   //ÒªÓõ½¶ÓÁÐ 
{ 
	TLGraph* tGraph = (TLGraph*)graph;
	int condition = 0;
	int* visited = (int*)calloc(tGraph->count,sizeof(int));
	
	condition = (tGraph!=NULL)&&(pFunc!=NULL);
	condition = condition && (v>=0) &&(v<tGraph->count);
	condition = condition &&  (visited!=NULL);
	
	if(condition)
	{
		int i = 0;
		bfs(tGraph,v,visited,pFunc);
		
		for(i=0;i<tGraph->count;i++)
		{
			if(!visited[i])
			{
				bfs(tGraph,i,visited,pFunc);	
			}	
		}
		printf("\n");		
	}
	free(visited);
}
void LGraph_Display(LGraph* graph,LGraph_Print* pFunc)
{
	TLGraph* tGraph = (TLGraph*)graph;
	if((tGraph!=NULL)&&(pFunc!=NULL))
	{
		int i = 0;
		int j = 0;
		for(i=0;i<tGraph->count;i++)
		{
			printf("%d: ",i);
			pFunc(tGraph->v[i]);
			printf(";");		
		}
			
		printf("\n");
		
		TListNode* node = NULL;//²»ÉêÇë¿Õ¼äÒ²ÊÇ¿ÉÒÔµÄ
		
		for(i=0;i<tGraph->count;i++)
		{
			
			for(j=0;j<LinkList_Length(tGraph->la[i]);j++)
			{
				//TListNode* node = NULL;//·ÅÔÚÕâÀïÓеãÀË·Ñ¿Õ¼ä 
				//TListNode* node = (TListNode*)malloc(sizeof(TListNode));   
				node = (TListNode*)LinkList_Get(tGraph->la[i],j);
				printf("< ");
				pFunc(tGraph->v[i]);
				printf(",");
				pFunc(tGraph->v[node->v]);
				printf(",w:%d",node->w);
				printf(">");
				printf(" ");
//				free(node);
//				node = NULL;
			}	
		}
		printf("\n");
	}
}

//main.c

/*----------------
* time:2016-4-14
-----------------*/


#include <stdio.h>
#include <stdlib.h>
#include "LGraph.h"
#include "stdio.h"

void print_data(LVertex* v)
{
	printf("%s",(char*)v);
}
int main(int argc, char *argv[]) 
{
	LVertex* v[] = {"A","B","C","D","E","F"};
	LGraph* graph = (LGraph*)LGraph_Create(v,6);
	
	LGraph_AddEdge(graph,0,1,2);
	LGraph_AddEdge(graph,0,2,2);
	LGraph_AddEdge(graph,1,2,4);
	LGraph_AddEdge(graph,1,3,6);
	LGraph_AddEdge(graph,2,4,6);
	LGraph_AddEdge(graph,3,2,6);
	LGraph_AddEdge(graph,3,5,6);

	
	printf("A->B:W = %d\n",LGraph_GetEdge(graph,0,1));
	printf("A Degree:%d\n",LGraph_TD(graph,0));
	printf("Vertex Count : %d\n",LGraph_VertexCount(graph));
	printf("Edge Count : %d\n",LGraph_EdgeCount(graph));
	
	LGraph_Display(graph,print_data);
	
	printf("\n");
	
	printf("DFS: ");
	LGraph_DFS(graph,0,print_data);
	
	printf("BFS: ");
	LGraph_BFS(graph,0,print_data);
	
	printf("\n");
	
	LGraph_Destroy(graph);
	return 0;
}











1

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/daa20/article/details/51159133
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞