Sum of the nodes of a Circular Linked List | Python3 program to find the sum of all nodes of a Circular linked list ; class for a node ; Function to insert a node at the beginning of a Circular linked list ; If linked list is not NULL then set the next of last node ; For the first node ; Function to find sum of the given Circular linked list ; Driver code ; Initialize lists as empty ; Created linked list will be 11 -> 2 -> 56 -> 12
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head , data ) : NEW_LINE INDENT if not head : NEW_LINE INDENT head = Node ( data ) NEW_LINE head . next = head NEW_LINE return head NEW_LINE DEDENT lnode = head NEW_LINE while ( lnode and lnode . next is not head ) : NEW_LINE INDENT lnode = lnode . next NEW_LINE DEDENT ptr1 = Node ( data ) NEW_LINE ptr1 . next = head NEW_LINE lnode . next = ptr1 NEW_LINE head = ptr1 NEW_LINE return head NEW_LINE DEDENT def sumOfList ( head ) : NEW_LINE INDENT temp = head NEW_LINE tsum = temp . data NEW_LINE temp = temp . next NEW_LINE while ( temp is not head ) : NEW_LINE INDENT tsum += temp . data NEW_LINE temp = temp . next NEW_LINE DEDENT return tsum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 56 ) NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 11 ) NEW_LINE print ( " Sum ▁ of ▁ circular ▁ list ▁ is ▁ = ▁ { } " . format ( sumOfList ( head ) ) ) NEW_LINE DEDENT