Sum of the nodes of a Circular Linked List | CPP program to find the sum of all nodes of a Circular linked list ; Structure 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int data ) { struct Node * ptr1 = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; struct Node * temp = * head_ref ; ptr1 -> data = data ; ptr1 -> next = * head_ref ; if ( * head_ref != NULL ) { while ( temp -> next != * head_ref ) temp = temp -> next ; temp -> next = ptr1 ; } else ptr1 -> next = ptr1 ; * head_ref = ptr1 ; } int sumOfList ( struct Node * head ) { struct Node * temp = head ; int sum = 0 ; if ( head != NULL ) { do { temp = temp -> next ; sum += temp -> data ; } while ( temp != head ) ; } return sum ; } int main ( ) { struct Node * head = NULL ; push ( & head , 12 ) ; push ( & head , 56 ) ; push ( & head , 2 ) ; push ( & head , 11 ) ; cout << " Sum ▁ of ▁ Circular ▁ linked ▁ list ▁ is ▁ = ▁ " << sumOfList ( head ) ; return 0 ; }