fork download
  1. #include <iostream>
  2. #include <cmath> // For abs()
  3.  
  4. // Definition of a Node in the linked list
  5. struct Node {
  6. int data;
  7. Node* next;
  8.  
  9. Node(int value) : data(value), next(nullptr) {}
  10. };
  11.  
  12. // Function to compute the sum of absolute differences in pairs
  13. int sumOfAbsoluteDifferences(Node* head) {
  14. if (!head || !head->next) {
  15. // If the list is empty or has only one node, return 0
  16. return 0;
  17. }
  18.  
  19. int sum = 0;
  20. Node* current = head;
  21.  
  22. // Traverse the list in pairs
  23. while (current && current->next) {
  24. sum += std::abs(current->data - current->next->data);
  25. current = current->next->next; // Move to the next pair
  26. }
  27.  
  28. return sum;
  29. }
  30.  
  31. // Helper function to append a node to the linked list
  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. // Helper function to print the linked list
  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. // Example usage
  56. int main() {
  57. Node* head = nullptr;
  58.  
  59. // Creating the linked list
  60. appendNode(head, 10);
  61. appendNode(head, 20);
  62. appendNode(head, 15);
  63. appendNode(head, 5);
  64.  
  65. // Printing the list
  66. std::cout << "Linked list: ";
  67. printList(head);
  68.  
  69. // Finding and printing the sum of absolute differences
  70. int result = sumOfAbsoluteDifferences(head);
  71. std::cout << "Sum of absolute differences: " << result << std::endl;
  72.  
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Linked list: 10 20 15 5 
Sum of absolute differences: 20