Skip to main content

Sum of the alternate nodes of Circular linked list

A circular linked list is a type of linked list where the last node points back to the first node, forming a circular structure. Each node contains data and a reference (or "next" pointer) to the next node in the sequence. The problem is to find the sum of the values of alternate nodes within a given circular linked list.

Problem Statement

Given a circular linked list, we need to develop a program that calculates and outputs the sum of the values of alternate nodes present in the list.

Example

Consider a circular linked list with the following nodes: 1 -> 4 -> 3 -> 7 -> 9 -> 11 -> 2

In this example, the sum of the values of alternate nodes (1 + 3 + 9 + 2) is 15.

Idea to Solve the Problem

Sum Alternating nodes

To find the sum of the values of alternate nodes in a circular linked list, we can traverse the list and maintain an indicator to keep track of whether we should add the current node's value to the sum. We start by adding the value of the first node and then alternate between adding and not adding the values of the subsequent nodes.

Pseudocode

alternateNodeSum(CircularLinkedList me):
    if me.head is null:
        return 0
    initialize sum = me.head.data
    initialize temp = me.head.next
    initialize status = 0
    while temp is not equal to me.head:
        if status is 1:
            add temp.data to sum
        change status to opposite value
        move temp to the next node
    return sum

Algorithm Explanation

  1. Check if the circular linked list is empty. If it is, return 0 as there are no nodes to calculate the sum.
  2. Initialize a variable sum with the data of the first node (me.head.data).
  3. Start traversing from the second node (temp = me.head.next).
  4. Initialize a variable status to 0. This indicator will determine whether we add the value of the current node to the sum.
  5. While the current node (temp) is not equal to the starting node (me.head), check the value of status.
  6. If status is 1, add the data of the current node (temp.data) to the sum.
  7. Change the value of status to the opposite (0 to 1 or 1 to 0).
  8. Move temp to the next node.
  9. After traversing the entire circular linked list, return the calculated sum.

Program List

Time Complexity

The time complexity of this algorithm is O(n), where n is the number of nodes in the circular linked list. We traverse the entire list once to calculate the sum of the values of alternate nodes.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment