Graph

A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph.  A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.

Program:

Python3




class adjnode:
    def __init__(self, val):
        self.val = val
        self.next = None
 
 
class graph:
    def __init__(self, vertices):
        self.v = vertices
        self.ele = [None]*self.v
 
    def edge(self, src, dest):
        node = adjnode(dest)
        node.next = self.ele[src]
        self.ele[src] = node
 
        node = adjnode(src)
        node.next = self.ele[dest]
        self.ele[dest] = node
 
    def __repr__(self):
        for i in range(self.v):
            print("Adjacency list of vertex {}\n head".format(i), end="")
            temp = self.ele[i]
            while temp:
                print(" -> {}".format(temp.val), end="")
                temp = temp.next
 
 
g = graph(4)
g.edge(0, 2)
g.edge(1, 3)
g.edge(3, 2)
g.edge(0, 3)
g.__repr__()


Output:

Adjacency list of vertex 0

head -> 3 -> 2

Adjacency list of vertex 1

head -> 3

Adjacency list of vertex 2

head -> 3 -> 0

Adjacency list of vertex 3

head -> 0 -> 2 -> 1

User Defined Data Structures in Python

In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures:

  • Non-primitive data types: Python has list, set, and dictionary as its non-primitive data types which can also be considered its in-built data structures.
  • User-defined data structures: Data structures that aren’t supported by python but can be programmed to reflect the same functionality using concepts supported by python are user-defined data structures. There are many data structure that can be implemented this way:

Similar Reads

Linked list

A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image:...

Stack

...

Queue

A stack is a linear structure that allows data to be inserted and removed from the same end thus follows a last in first out(LIFO) system. Insertion and deletion is known as push() and pop() respectively....

Tree

...

Graph

A queue is a linear structure that allows insertion of elements from one end and deletion from the other. Thus it follows, First In First Out(FIFO) methodology. The end which allows deletion is known as the front of the queue and the other end is known as the rear end of the queue....

Hashmap

...

Contact Us