#include <bits/stdc++.h>
#include <cmath>
using namespace std;
struct Node {
int data;
Node* next;
};
int sumOfAbsoluteDifferences(Node* root) {
if (!root || !root->next) {
return 0;
}
int sum = 0;
Node* current = root;
while (current && current->next) {
sum += abs(current->data - current->next->data);
current = current->next->next;
}
return sum;
}
void appendNode(Node*& root, int value) {
if (!root) {
root = new Node();
return;
}
Node* current = root;
while (current->next) {
current = current->next;
}
current->next = new Node();
}
void print(Node* root) {
Node* current = root;
while (current) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
int main() {
Node* root= NULL;
appendNode(root, 10);
appendNode(root, 20);
appendNode(root, 15);
appendNode(root, 5);
std::cout << "Linked list: ";
print(root);
int result = sumOfAbsoluteDifferences(root);
cout << "Sum of absolute differences: " << result << endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CiNpbmNsdWRlIDxjbWF0aD4gCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgoKc3RydWN0IE5vZGUgewogICAgaW50IGRhdGE7CiAgICBOb2RlKiBuZXh0OwoKICAgIAp9OwoKCmludCBzdW1PZkFic29sdXRlRGlmZmVyZW5jZXMoTm9kZSogcm9vdCkgewogICAgaWYgKCFyb290IHx8ICFyb290LT5uZXh0KSB7CiAgICAgICAgCiAgICAgICAgcmV0dXJuIDA7CiAgICB9CgogICAgaW50IHN1bSA9IDA7CiAgICBOb2RlKiBjdXJyZW50ID0gcm9vdDsKCiAgIAogICAgd2hpbGUgKGN1cnJlbnQgJiYgY3VycmVudC0+bmV4dCkgewogICAgICAgIHN1bSArPSBhYnMoY3VycmVudC0+ZGF0YSAtIGN1cnJlbnQtPm5leHQtPmRhdGEpOwogICAgICAgIGN1cnJlbnQgPSBjdXJyZW50LT5uZXh0LT5uZXh0OwogICAgfQoKICAgIHJldHVybiBzdW07Cn0KCgp2b2lkIGFwcGVuZE5vZGUoTm9kZSomIHJvb3QsIGludCB2YWx1ZSkgewogICAgaWYgKCFyb290KSB7CiAgICAgICAgcm9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