#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+CgoKc3RydWN0IE5vZGUgewogICAgaW50IGRhdGE7CiAgICBOb2RlKiBuZXh0OwoKICAgIE5vZGUoaW50IHZhbHVlKSA6IGRhdGEodmFsdWUpLCBuZXh0KG51bGxwdHIpIHt9Cn07CgoKaW50IHN1bU9mQWJzb2x1dGVEaWZmZXJlbmNlcyhOb2RlKiBoZWFkKSB7CiAgICBpZiAoIWhlYWQgfHwgIWhlYWQtPm5leHQpIHsKICAgICAgICAKICAgICAgICByZXR1cm4gMDsKICAgIH0KCiAgICBpbnQgc3VtID0gMDsKICAgIE5vZGUqIGN1cnJlbnQgPSBoZWFkOwoKICAgIAogICAgd2hpbGUgKGN1cnJlbnQgJiYgY3VycmVudC0+bmV4dCkgewogICAgICAgIHN1bSArPSBzdGQ6OmFicyhjdXJyZW50LT5kYXRhIC0gY3VycmVudC0+bmV4dC0+ZGF0YSk7CiAgICAgICAgY3VycmVudCA9IGN1cnJlbnQtPm5leHQtPm5leHQ7CiAgICB9CgogICAgcmV0dXJuIHN1bTsKfQoKCnZvaWQgYXBwZW5kTm9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