Problem 276600 · easy · Phase 02 Linear Data Structures

Alternating Sum of a List

linked list · traversal · arithmetic

Given the head of a singly linked list, return its alternating sum: add the first value, subtract the second, add the third, subtract the fourth, and so on. Return 0 for an empty list.

Examples

Input:  head = 5 -> 3 -> 8 -> 1
Output: 9
Explanation: 5 - 3 + 8 - 1 = 9

Input:  head = 7
Output: 7

Constraints

  • 0 <= number of nodes <= 10**4
  • -10**6 <= node value <= 10**6
  • Target: O(n) time, one pass

Goals

  • Accumulate a value while walking a linked list
  • Flip a sign on every step
Starting Python…