-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathAdjacencyList.cpp
More file actions
78 lines (71 loc) · 1.68 KB
/
AdjacencyList.cpp
File metadata and controls
78 lines (71 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <cstdlib>
using namespace std;
struct AdjListNode
{
int dest;
struct AdjListNode* next;
};
struct AdjList
{
struct AdjListNode *head;
};
class Graph
{
private:
int V;
struct AdjList* array;
public:
Graph(int V)
{
this->V = V;
array = new AdjList [V];
for (int i = 0; i < V; ++i)
array[i].head = NULL;
}
AdjListNode* newAdjListNode(int dest)
{
AdjListNode* newNode = new AdjListNode;
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
void addEdge(int src, int dest)
{
AdjListNode* newNode = newAdjListNode(dest);
newNode->next = array[src].head;
array[src].head = newNode;
newNode = newAdjListNode(src);
newNode->next = array[dest].head;
array[dest].head = newNode;
}
void printGraph()
{
int v;
for (v = 0; v < V; ++v)
{
AdjListNode* pCrawl = array[v].head;
cout<<"\n Adjacency list of vertex "<<v<<"\n head ";
while (pCrawl)
{
cout<<"-> "<<pCrawl->dest;
pCrawl = pCrawl->next;
}
cout<<endl;
}
}
};
int main()
{
Graph gh(5);
gh.addEdge(0, 1);
gh.addEdge(0, 4);
gh.addEdge(1, 2);
gh.addEdge(1, 3);
gh.addEdge(1, 4);
gh.addEdge(2, 3);
gh.addEdge(3, 4);
// print the adjacency list representation of the above graph
gh.printGraph();
return 0;
}