#include <iostream>
#include <cmath>
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
int sumOfAbsoluteDifferences(Node* head) {
if (!head || !head->next) {
return 0;
}
int sum = 0;
Node* current = head;
while (current && current->next) {
sum += std::abs(current->data - current->next->data);
current = current->next->next;
}
return sum;
}
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);
}
void printList(Node* head) {
Node* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}
int main() {
Node* head = nullptr;
appendNode(head, 10);
appendNode(head, 20);
appendNode(head, 15);
appendNode(head, 5);
std::cout << "Linked list: ";
printList(head);
int result = sumOfAbsoluteDifferences(head);
std::cout << "Sum of absolute differences: " << result << std::endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y21hdGg+IAoKCnN0cnVjdCBOb2RlIHsKICAgIGludCBkYXRhOwogICAgTm9kZSogbmV4dDsKCiAgICBOb2RlKGludCB2YWx1ZSkgOiBkYXRhKHZhbHVlKSwgbmV4dChudWxscHRyKSB7fQp9OwoKCmludCBzdW1PZkFic29sdXRlRGlmZmVyZW5jZXMoTm9kZSogaGVhZCkgewogICAgaWYgKCFoZWFkIHx8ICFoZWFkLT5uZXh0KSB7CiAgICAgICAgCiAgICAgICAgcmV0dXJuIDA7CiAgICB9CgogICAgaW50IHN1bSA9IDA7CiAgICBOb2RlKiBjdXJyZW50ID0gaGVhZDsKCiAgIAogICAgd2hpbGUgKGN1cnJlbnQgJiYgY3VycmVudC0+bmV4dCkgewogICAgICAgIHN1bSArPSBzdGQ6OmFicyhjdXJyZW50LT5kYXRhIC0gY3VycmVudC0+bmV4dC0+ZGF0YSk7CiAgICAgICAgY3VycmVudCA9IGN1cnJlbnQtPm5leHQtPm5leHQ7CiAgICB9CgogICAgcmV0dXJuIHN1bTsKfQoKCnZvaWQgYXBwZW5kTm9kZShO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