fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct node
  5. {
  6. int value = 0;
  7. node *next = nullptr;
  8. };
  9.  
  10. node* get_node_at(node *head, int index, node **previous = nullptr)
  11. {
  12. if (previous) *previous = nullptr;
  13.  
  14. if ((!head) || (index < 0)) return nullptr;
  15.  
  16. node *temp = head;
  17. while (index > 0)
  18. {
  19. if (!temp) return nullptr;
  20. if (previous) *previous = temp;
  21. temp = temp->next;
  22. --index;
  23. }
  24.  
  25. return temp;
  26. }
  27.  
  28. void swap_nodes(node *&head, int i, int j)
  29. {
  30. if ((!head) || (i == j)) return;
  31.  
  32. node *previous_i, *previous_j;
  33. node* temp_i = get_node_at(head, i, &previous_i);
  34. node* temp_j = get_node_at(head, j, &previous_j);
  35.  
  36. if (!temp_i || !temp_j)
  37. return;
  38.  
  39. if (previous_i)
  40. previous_i->next = temp_j;
  41.  
  42. if (previous_j)
  43. previous_j->next = temp_i;
  44.  
  45. node *temp = temp_i->next;
  46. temp_i->next = temp_j->next;
  47. temp_j->next = temp;
  48.  
  49. if (temp_i == head)
  50. head = temp_j;
  51. else if (temp_j == head)
  52. head = temp_i;
  53. }
  54.  
  55. int main()
  56. {
  57. node *head = nullptr;
  58. node **ptr = &head;
  59.  
  60. for (int i = 1; i <= 5; ++i)
  61. {
  62. *ptr = new node;
  63. (*ptr)->value = i;
  64. ptr = &((*ptr)->next);
  65. }
  66.  
  67. cout << "Before: ";
  68. for(node *temp = head; temp != nullptr; temp = temp->next)
  69. cout << temp->value << " ";
  70. cout << endl;
  71.  
  72. swap_nodes(head, 0, 4);
  73. swap_nodes(head, 1, 3);
  74.  
  75. cout << "After: ";
  76. for(node *temp = head; temp != nullptr; temp = temp->next)
  77. cout << temp->value << " ";
  78. cout << endl;
  79.  
  80. for(node *temp = head; temp != nullptr;)
  81. {
  82. node *n = temp;
  83. temp = temp->next;
  84. delete n;
  85. }
  86.  
  87. return 0;
  88. }
Success #stdin #stdout 0s 4392KB
stdin
Standard input is empty
stdout
Before: 1 2 3 4 5 
After: 5 4 3 2 1