-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.cpp
117 lines (94 loc) · 2.21 KB
/
graph.cpp
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <iostream>
using namespace std;
struct Node //adjacency list
{
int val;
Node* next;
};
struct Ver //vertices
{
int src, dest;
};
class Graph
{
Node* getAdjListNode(int dest, Node* head) // Function to allocate new node of Adjacency List
{
Node* newNode = new Node;
newNode->val = dest;
newNode->next = head; // point new node to current head
return newNode;
}
int N;
public:
// An array of pointers to Node to represent
// adjacency list
Node **head;
// Constructor
Graph(Edge edges[], int n, int N)
{
// allocate memory
head = new Node*[N]();
this->N = N;
// initialize head pointer for all vertices
for (int i = 0; i < N; i++)
head[i] = nullptr;
// add edges to the directed graph
for (unsigned i = 0; i < n; i++)
{
int src = edges[i].src;
int dest = edges[i].dest;
// insert in the beginning
Node* newNode = getAdjListNode(dest, head[src]);
// point head pointer to new node
head[src] = newNode;
// Uncomment below lines for undirected graph
/*
newNode = getAdjListNode(src, head[dest]);
// change head pointer to point to the new node
head[dest] = newNode;
*/
}
}
// Destructor
~Graph() {
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
}
};
// print all neighboring vertices of given vertex
void printList(Node* ptr)
{
while (ptr != nullptr)
{
cout << " -> " << ptr->val << " ";
ptr = ptr->next;
}
cout << endl;
}
// Graph Implementation in C++ without using STL
int main()
{
// array of graph edges as per above diagram.
Edge edges[] =
{
// pair (x, y) represents edge from x to y
{ 0, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 },
{ 3, 2 }, { 4, 5 }, { 5, 4 }
};
// Number of vertices in the graph
int N = 6;
// calculate number of edges
int n = sizeof(edges)/sizeof(edges[0]);
// construct graph
Graph graph(edges, n, N);
// print adjacency list representation of graph
for (int i = 0; i < N; i++)
{
// print given vertex
cout << i << " --";
// print all its neighboring vertices
printList(graph.head[i]);
}
return 0;
}