Jaideep Singh
Jaideep Singh

Reputation: 63

Difficulty in understanding Graph with adjacency list representation using nodes{linked list way}

class AdjNode: 
    def __init__(self, data): 
        self.vertex = data 
        self.next = None

Size of the array will be the no. of the 
# vertices "V" 
class Graph: 
    def __init__(self, vertices): 
        self.V = vertices 
        self.graph = [None] * self.V 

    # Function to add an edge in an undirected graph 
    def add_edge(self, src, dest): 
        # Adding the node to the source node 
        node = AdjNode(dest) 
#from here
        node.next = self.graph[src] 
        self.graph[src] = node
#to here 
        node = AdjNode(src) 
        node.next = self.graph[dest] 
        self.graph[dest] = node

if __name__ == "__main__": 
    V = 5
    graph = Graph(V) 
    graph.add_edge(0, 1) 
    graph.add_edge(0, 4) 
    graph.add_edge(1, 2) 
    graph.add_edge(1, 3) 
    graph.add_edge(1, 4) 

    graph.print_graph() 

I did not understand the from here to here partin comments. Please explain. I even tried python tutor visualizer. Understood everything else though. This code is from geeksforgeeks page https://www.geeksforgeeks.org/graph-and-its-representations/ Any help would be appreciated.

Upvotes: 0

Views: 217

Answers (1)

DarrylG
DarrylG

Reputation: 17156

Explanation

The lines of code in question are the standard way of inserting an item at the beginning of a linked list.

Reference

Steps

  1. Create a new node
node = AdjNode(dest)
  1. Place new node at the head of the list

    Done by updating its next to the existing head of the list

node.next = self.graph[src] 
  1. Assign the head to the new node
self.graph[src] = node

Upvotes: 2

Related Questions