fork download
  1. #include <iostream>
  2. #include <cmath> // For std::abs
  3.  
  4. // Definition of a Node in the linked list
  5. struct Node {
  6. int data;
  7. Node* next;
  8.  
  9. Node(int val) : data(val), next(nullptr) {}
  10. };
  11.  
  12. // Function to calculate the sum of absolute differences of all pairs
  13. int sumOfAbsoluteDifferences(Node* root) {
  14. if (!root) return 0; // If the list is empty
  15.  
  16. int sum = 0;
  17. Node* ptr1 = root;
  18.  
  19. while (ptr1) {
  20. Node* ptr2 = ptr1->next;
  21. while (ptr2) {
  22. sum += std::abs(ptr1->data - ptr2->data);
  23. ptr2 = ptr2->next;
  24. }
  25. ptr1 = ptr1->next;
  26. }
  27.  
  28. return sum;
  29. }
  30.  
  31. // Utility function to add a node at the end of the list
  32. void appendNode(Node*& head, int value) {
  33. if (!head) {
  34. head = new Node(value);
  35. return;
  36. }
  37. Node* temp = head;
  38. while (temp->next) temp = temp->next;
  39. temp->next = new Node(value);
  40. }
  41.  
  42. // Utility function to print a linked list
  43. void printList(Node* head) {
  44. while (head) {
  45. std::cout << head->data << " -> ";
  46. head = head->next;
  47. }
  48. std::cout << "NULL\n";
  49. }
  50.  
  51. int main() {
  52. // Example usage
  53. Node* head = nullptr;
  54. appendNode(head, 1);
  55. appendNode(head, 3);
  56. appendNode(head, 5);
  57.  
  58. printList(head); // Output: 1 -> 3 -> 5 -> NULL
  59.  
  60. int result = sumOfAbsoluteDifferences(head);
  61. std::cout << "Sum of absolute differences: " << result << std::endl; // Output: 8
  62.  
  63. return 0;
  64. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
1 -> 3 -> 5 -> NULL
Sum of absolute differences: 8