e-olymp
favorite We need a little bit of your help to keep things running, click on this banner to learn more
Competitions

class LinkedList

LinkedList Sum

Given a linked list, find the sum of its elements.

Definition of a single linked list:

// Java
class ListNode {
  int val;
  ListNode next;
  ListNode(int x) {
    val = x;
    next = null;
  }
}
// C++
class ListNode
{
public:
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};

Implement function sum to find the sum of linked list elements.

// Java
int sum(ListNode head)
// C++
int sum(ListNode *head)

Example

prb9898.gif

The sum of elements of a linked list is 6.

Time limit 1 second
Memory limit 128 MiB
Author Mykhailo Medvediev