首页 > 代码库 > GeeksforGeeks - Adjacency List邻接矩阵C代码

GeeksforGeeks - Adjacency List邻接矩阵C代码

邻接矩阵的图示:

Adjacency List Representation of Graph

构建一个这样的无向邻接矩阵。

参考网站: http://www.geeksforgeeks.org/graph-and-its-representations/

这里写了个类,增加删除图的操作。

#pragma once
#include <stdio.h>
#include <stdlib.h>

class AdjListGraph
{
	struct Node
	{
		int dest;
		Node *next;
	};

	struct List
	{
		Node *first;
	};

	struct Graph
	{
		int vers;
		List *verArr;
	};

	Node *createNode(int dest)
	{
		Node *newNode = (Node *) malloc(sizeof(Node));
		newNode->dest = dest;
		newNode->next = nullptr;
		return newNode;
	}

	Graph *createGraph(int vers)
	{
		Graph * gra = (Graph *) malloc(sizeof(Graph));
		gra->vers = vers;
		gra->verArr = (List *) malloc(vers * sizeof(List));
		for (int i = 0; i < vers; i++)
		{
			gra->verArr[i].first = nullptr;
		}
		return gra;
	}

	void addEdge(Graph *gra, int src, int dest)
	{
		Node *n = createNode(dest);
		n->next = gra->verArr[src].first;//这里不需要->next,因为无空head指针
		gra->verArr[src].first = n;

		//构造无向图
		n = createNode(src);
		n->next = gra->verArr[dest].first;
		gra->verArr[dest].first = n;
	}
	
	void printGraph()
	{
		for (int i = 0; i < graph->vers; i++)
		{
			Node *n = graph->verArr[i].first;
			printf("\n Adjacency list of vertex %d\n head ", i);
			while (n)
			{
				printf("-> %d", n->dest);
				n = n->next;
			}
			putchar(‘\n‘);
		}
	}

	Graph *graph;
public:
	AdjListGraph(int V = 0) : graph(nullptr)
	{
		graph = createGraph(V);
		addEdge(graph, 0, 1);
		addEdge(graph, 0, 4);
		addEdge(graph, 1, 2);
		addEdge(graph, 1, 3);
		addEdge(graph, 1, 4);
		addEdge(graph, 2, 3);
		addEdge(graph, 3, 4);
		printGraph();
	}

	~AdjListGraph()
	{
		if (graph)
		{
			for (int i = 0; i < graph->vers; i++)
			{
				Node *n = graph->verArr[i].first;
				Node *p = nullptr;
				while (n)
				{
					p = n;
					n = n->next;
					free(p);
				}
			}
			free(graph->verArr);
			free(graph);
		}
	}
};