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