fork download
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4.  
  5. struct Node {
  6. int data;
  7. Node* next;
  8.  
  9. Node(int value) : data(value), next(nullptr) {}
  10. };
  11.  
  12.  
  13. int sumOfAbsoluteDifferences(Node* head) {
  14. if (!head || !head->next) {
  15.  
  16. return 0;
  17. }
  18.  
  19. int sum = 0;
  20. Node* current = head;
  21.  
  22.  
  23. while (current && current->next) {
  24. sum += std::abs(current->data - current->next->data);
  25. current = current->next->next;
  26. }
  27.  
  28. return sum;
  29. }
  30.  
  31.  
  32. void appendNode(Node*& head, int value) {
  33. if (!head) {
  34. head = new Node(value);
  35. return;
  36. }
  37.  
  38. Node* current = head;
  39. while (current->next) {
  40. current = current->next;
  41. }
  42. current->next = new Node(value);
  43. }
  44.  
  45.  
  46. void printList(Node* head) {
  47. Node* current = head;
  48. while (current) {
  49. std::cout << current->data << " ";
  50. current = current->next;
  51. }
  52. std::cout << std::endl;
  53. }
  54.  
  55.  
  56. int main() {
  57. Node* head = nullptr;
  58.  
  59.  
  60. appendNode(head, 10);
  61. appendNode(head, 20);
  62. appendNode(head, 15);
  63. appendNode(head, 5);
  64.  
  65.  
  66. std::cout << "Linked list: ";
  67. printList(head);
  68.  
  69.  
  70. int result = sumOfAbsoluteDifferences(head);
  71. std::cout << "Sum of absolute differences: " << result << std::endl;
  72.  
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0s 5276KB
stdin
Standard input is empty
stdout
Linked list: 10 20 15 5 
Sum of absolute differences: 20