#include <iostream>
#include <cmath> // For abs()
// Definition of a Node in the linked list
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
// Function to compute the sum of absolute differences in pairs
int sumOfAbsoluteDifferences(Node* head) {
if (!head || !head->next) {
// If the list is empty or has only one node, return 0
return 0;
}
int sum = 0;
Node* current = head;
// Traverse the list in pairs
while (current && current->next) {
sum += std::abs(current->data - current->next->data);
current = current->next->next; // Move to the next pair
}
return sum;
}
// Helper function to append a node to the linked list
void appendNode(Node*& head, int value) {
if (!head) {
head = new Node(value);
return;
}
Node* current = head;
while (current->next) {
current = current->next;
}
current->next = new Node(value);
}
// Helper function to print the linked list
void printList(Node* head) {
Node* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
// Example usage
int main() {
Node* head = nullptr;
// Creating the linked list
appendNode(head, 10);
appendNode(head, 20);
appendNode(head, 15);
appendNode(head, 5);
// Printing the list
std::cout << "Linked list: ";
printList(head);
// Finding and printing the sum of absolute differences
int result = sumOfAbsoluteDifferences(head);
std::cout << "Sum of absolute differences: " << result << std::endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y21hdGg+IC8vIEZvciBhYnMoKQoKLy8gRGVmaW5pdGlvbiBvZiBhIE5vZGUgaW4gdGhlIGxpbmtlZCBsaXN0CnN0cnVjdCBOb2RlIHsKICAgIGludCBkYXRhOwogICAgTm9kZSogbmV4dDsKCiAgICBOb2RlKGludCB2YWx1ZSkgOiBkYXRhKHZhbHVlKSwgbmV4dChudWxscHRyKSB7fQp9OwoKLy8gRnVuY3Rpb24gdG8gY29tcHV0ZSB0aGUgc3VtIG9mIGFic29sdXRlIGRpZmZlcmVuY2VzIGluIHBhaXJzCmludCBzdW1PZkFic29sdXRlRGlmZmVyZW5jZXMoTm9kZSogaGVhZCkgewogICAgaWYgKCFoZWFkIHx8ICFoZWFkLT5uZXh0KSB7CiAgICAgICAgLy8gSWYgdGhlIGxpc3QgaX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