9898. 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) {}

};

 

// C

struct ListNode

{

  int val;

  struct ListNode* next;

};

 

Implement function sum that finds the sum of linked list elements.

 

// Java

int sum(ListNode head)

 

// C, C++

int sum(ListNode *head)

 

Example

The sum of elements of a linked list is 6.

 

 

SOLUTION

linked list

 

Algorithm analysis

Move through the list from the start to the end and sum up the values of all its elements.

 

Algorithm realization

Compute the sum of the list elements in the res variable.

 

int sum(ListNode *head)

{

  int res = 0;

 

Move forward through the list until head becomes NULL. Add to res the current value of the list element head->val.

 

  while (head != NULL)

  {

    res += head->val;

    head = head->next;

  }

  return res;

}

 

Java realization

 

int sum(ListNode head)

{

  int res = 0;

  while(head != null)

  {

    res += head.val;

    head = head.next;

  }

  return res;

}