#include <iostream>
#include <cmath> // For std::abs
// Definition of a Node in the linked list
struct Node {
int data;
Node* next;
Node(int val) : data(val), next(nullptr) {}
};
// Function to calculate the sum of absolute differences of all pairs
int sumOfAbsoluteDifferences(Node* root) {
if (!root) return 0; // If the list is empty
int sum = 0;
Node* ptr1 = root;
while (ptr1) {
Node* ptr2 = ptr1->next;
while (ptr2) {
sum += std::abs(ptr1->data - ptr2->data);
ptr2 = ptr2->next;
}
ptr1 = ptr1->next;
}
return sum;
}
// Utility function to add a node at the end of the list
void appendNode(Node*& head, int value) {
if (!head) {
head = new Node(value);
return;
}
Node* temp = head;
while (temp->next) temp = temp->next;
temp->next = new Node(value);
}
// Utility function to print a linked list
void printList(Node* head) {
while (head) {
std::cout << head->data << " -> ";
head = head->next;
}
std::cout << "NULL\n";
}
int main() {
// Example usage
Node* head = nullptr;
appendNode(head, 3.5);
appendNode(head, 7.3);
printList(head); // Output: 1 -> 3 -> 5 -> NULL
int result = sumOfAbsoluteDifferences(head);
std::cout << "Sum of absolute differences: " << result << std::endl; // Output: 8
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y21hdGg+IC8vIEZvciBzdGQ6OmFicwoKLy8gRGVmaW5pdGlvbiBvZiBhIE5vZGUgaW4gdGhlIGxpbmtlZCBsaXN0CnN0cnVjdCBOb2RlIHsKICAgIGludCBkYXRhOwogICAgTm9kZSogbmV4dDsKICAgIAogICAgTm9kZShpbnQgdmFsKSA6IGRhdGEodmFsKSwgbmV4dChudWxscHRyKSB7fQp9OwoKLy8gRnVuY3Rpb24gdG8gY2FsY3VsYXRlIHRoZSBzdW0gb2YgYWJzb2x1dGUgZGlmZmVyZW5jZXMgb2YgYWxsIHBhaXJzCmludCBzdW1PZkFic29sdXRlRGlmZmVyZW5jZXMoTm9kZSogcm9vdCkgewogICAgaWYgKCFyb290KSByZXR1cm4gMDsgLy8gSWYgdGhlIGxpc3QgaXMgZW1wdHkKICAgIAogICAgaW50IHN1bSA9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