fork download
  1. #include <iostream>
  2. #include <cmath> // For std::abs
  3.  
  4. // Define a Node structure for the linked list
  5. struct Node {
  6. double data;
  7. Node* next;
  8.  
  9. Node(double value) : data(value), next(nullptr) {}
  10. };
  11.  
  12. // Function to find the sum of the absolute differences of all pairs
  13. double sumOfAbsoluteDifferences(Node* root) {
  14. double sum = 0.0;
  15. for (Node* i = root; i != nullptr; i = i->next) {
  16. for (Node* j = root; j != nullptr; j = j->next) {
  17. sum += std::abs(i->data - j->data);
  18. }
  19. }
  20. return sum / 2; // To avoid double counting
  21. }
  22.  
  23. // Helper function to add a new node to the list
  24. void append(Node*& root, double value) {
  25. if (root == nullptr) {
  26. root = new Node(value);
  27. } else {
  28. Node* temp = root;
  29. while (temp->next != nullptr) {
  30. temp = temp->next;
  31. }
  32. temp->next = new Node(value);
  33. }
  34. }
  35.  
  36. // Main function to test the implementation
  37. int main() {
  38. Node* root = nullptr;
  39.  
  40. // Input: 3.5, 7.3
  41. append(root, 3.5);
  42. append(root, 7.3);
  43.  
  44. // Calculate and output the result
  45. std::cout << "Sum of absolute differences: " << sumOfAbsoluteDifferences(root) << std::endl;
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
Sum of absolute differences: 3.8