Sum of the nodes of a Circular Linked List | Java 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
import java . util . * ; class GFG { static class Node { int data ; Node next ; } ; static Node push ( Node head_ref , int data ) { Node ptr1 = new Node ( ) ; 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 ; return head_ref ; } static int sumOfList ( Node head ) { Node temp = head ; int sum = 0 ; if ( head != null ) { do { temp = temp . next ; sum += temp . data ; } while ( temp != head ) ; } return sum ; } public static void main ( String args [ ] ) { Node head = null ; head = push ( head , 12 ) ; head = push ( head , 56 ) ; head = push ( head , 2 ) ; head = push ( head , 11 ) ; System . out . println ( " Sum ▁ of ▁ Circular ▁ linked " + " ▁ list ▁ is ▁ = ▁ " + sumOfList ( head ) ) ; } }