euisblue
Array[C++] Binary SearchGraph[Ruby] Adjacency ListMath[C++] Manhattan Distance[C++] Euclidean Distance[C++] Chebyshev DistanceQueue[Ruby] Linked List Implementation[Ruby] Array ImplementationStack[Ruby] Linked List Implementation[Ruby] Array Implementation

Adjacency List


1class Node 2 attr_accessor :data, :next 3 4 def initialize(data) 5 @data = data 6 @next = nil 7 end 8end 9 10class AdjList 11 def initialize(v) 12 @graph = [] 13 @v = v 14 end 15 16 def add_edge(src, dest) 17 if @graph[src] 18 @graph[src].append(dest) 19 elsif @graph[src] == nil 20 @graph[src] = [dest] 21 end 22 23 if @graph[dest] 24 @graph[dest].append(src) 25 elsif @graph[dest] == nil 26 @graph[dest] = [src] 27 end 28 end 29 30 def display 31 for i in 0...@v 32 puts "Adjacency list of vertex #{i}" 33 print "head" 34 temp = @graph[i] 35 temp.each do |data| 36 print " -> #{data}" 37 end 38 puts 39 end 40 end 41 42end 43 44v = 5 45graph = AdjList.new(v) 46graph.add_edge(0, 1) 47graph.add_edge(0, 4) 48graph.add_edge(1, 2) 49graph.add_edge(1, 3) 50graph.add_edge(1, 4) 51graph.add_edge(2, 3) 52graph.add_edge(3, 4) 53 54graph.display