-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadjlist.cpp
More file actions
85 lines (70 loc) · 1.71 KB
/
adjlist.cpp
File metadata and controls
85 lines (70 loc) · 1.71 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
79
80
81
82
83
84
85
#include <iostream>
using namespace std;
class Node {
public:
int vertex;
Node* next;
Node(int v) {
vertex = v;
next = nullptr;
}
~Node() {
cout << "Deleted node with vertex " << vertex << endl;
}
};
class Graph {
int V;
Node** adjList; // Array of linked lists
public:
Graph(int vertices) {
V = vertices;
adjList = new Node*[V];
for (int i = 0; i < V; i++)
adjList[i] = nullptr; // Initialize list heads as NULL
}
void addEdge(int u, int v) {
Node* newNode = new Node(v);
newNode->next = adjList[u];
adjList[u] = newNode;
newNode = new Node(u); // Add edge for undirected graph
newNode->next = adjList[v];
adjList[v] = newNode;
}
void displayGraph() {
for (int i = 0; i < V; i++) {
cout << "Adjacency list of vertex " << i << ": ";
Node* temp = adjList[i];
while (temp) {
cout << temp->vertex << " ";
temp = temp->next;
}
cout << endl;
}
}
~Graph() {
for (int i = 0; i < V; i++) {
Node* temp = adjList[i];
while (temp) {
Node* nextNode = temp->next;
delete temp;
temp = nextNode;
}
}
delete[] adjList;
cout << "Graph deleted\n";
}
};
int main() {
int V, E;
cout << "Enter number of vertices and edges: ";
cin >> V >> E;
Graph graph(V);
cout << "Enter edges (u v):\n";
for (int i = 0; i < E; i++) {
int u, v;
cin >> u >> v;
graph.addEdge(u, v);
}
graph.displayGraph();
return 0;
}