# Adjacency list representation of directed graph in swift

Swift program for Adjacency list representation of directed graph. Here problem description and explanation.

``````import Foundation
/*
Swift 4 Program for
Directed graph representation using adjacency list
*/
class AjlistNode
{
// Vertices node key
var id: Int;
var next: AjlistNode? ;
init(_ id: Int)
{
// Set value of node key
self.id = id;
self.next = nil;
}
}
class Vertices
{
var data: Int;
var next: AjlistNode? ;
var last: AjlistNode? ;
init(_ data: Int)
{
self.data = data;
self.next = nil;
self.last = nil;
}
}
class Graph
{
// Number of Vertices
var size: Int;
var node: [Vertices?];
init(_ size: Int)
{
// Set value
self.size = size;
self.node = Array(repeating: nil, count: size);
self.setData();
}
// Set initial node value
func setData()
{
if (self.size <= 0)
{
print("\nEmpty Graph");
}
else
{
do {
var index: Int = 0;
while (index < self.size)
{
// Set initial node value
self.node[index] = Vertices(index);
index += 1;
}
}
}
}
// Connect two nodes
func connect(_ start: Int, _ last: Int)
{
let edge: AjlistNode? = AjlistNode(last);
if (self.node[start]!.next == nil)
{
self.node[start]!.next = edge;
}
else
{
// Add edge at the end
self.node[start]!.last!.next = edge;
}
// Get last edge
self.node[start]!.last = edge;
}
//  Handling the request of adding new edge
func addEdge(_ start: Int, _ last: Int)
{
if (start >= 0 && start < self.size &&
last >= 0 && last < self.size)
{
// Safe connection
self.connect(start, last);
}
else
{
// When invalid nodes
print("\nHere Something Wrong");
}
}
func printGraph()
{
if (self.size > 0)
{
do {
var index: Int = 0;
// Print graph ajlist Node value
while (index < self.size)
{
index ,
terminator: " :");
var temp: AjlistNode? = self.node[index]!.next;
while (temp  != nil)
{
// Display graph node
print(" ",self.node[temp!.id]!.data,
terminator: " ");
// visit to next edge
temp = temp!.next;
}
index += 1;
}
}
}
}
static func main(_ args: [String])
{
// 5 implies the number of nodes in graph
let g: Graph? = Graph(5);
// Connect node with an edge
// print graph element
g!.printGraph();
}
}
Graph.main([String]());``````

Output

``````Adjacency list of vertex  0 :  1
Adjacency list of vertex  1 :  2   4
Adjacency list of vertex  2 :  0   3
Adjacency list of vertex  3 :
Adjacency list of vertex  4 :  3``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.