-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgraph_implememt.cpp
99 lines (73 loc) · 1.28 KB
/
graph_implememt.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
#include <iostream>
using namespace std;
struct Node {
int val;
Node* next;
};
struct Edge {
int src, dest;
};
class graph
{
Node* getadjnodes(int dest, Node* head)
{
Node* newNode = new Node;
newNode->val = dest;
newNode->next = head;
return newNode;
}
int N;
public:
Node **head;
graph(Edge edges[], int n, int N)
{
head = new Node*[N]();
this->N = N;
for (int i = 0; i < N; i++)
head[i] = nullptr;
for (unsigned i = 0; i < n; i++)
{
int src = edges[i].src;
int dest = edges[i].dest;
Node* newNode = getadjnodes(dest, head[src]);
head[src] = newNode;
// Uncomment below lines for undirected graph
/*
newNode = getadjnodes(src, head[dest]);
// change head pointer to point to the new node
head[dest] = newNode;
*/
}
}
~graph() {
for (int i = 0; i < N; i++)
delete[] head[i];
delete[] head;
}
};
void printList(Node* ptr)
{
while (ptr != nullptr)
{
cout << " -> " << ptr->val << " ";
ptr = ptr->next;
}
cout << endl;
}
int main()
{
Edge edges[] =
{
{ 0, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 },
{ 3, 2 }, { 4, 5 }, { 5, 4 }
};
int N = 6;
int n = sizeof(edges)/sizeof(edges[0]);
graph graph(edges, n, N);
for (int i = 0; i < N; i++)
{
cout << i << " --";
printList(graph.head[i]);
}
return 0;
}