fork download
  1. #include <iostream>
  2.  
  3. struct Node
  4. {
  5. int data;
  6. Node *next;
  7. };
  8.  
  9. Node* push(Node *head, const int i)
  10. {
  11. Node *elem = new Node;
  12. elem->data = i;
  13.  
  14. if (!head)
  15. elem->next = nullptr;
  16. else
  17. elem->next = head;
  18. return elem;
  19. }
  20.  
  21. void print(Node *head)
  22. {
  23. while (head)
  24. {
  25. std::cout << head->data << " ";
  26. head = head->next;
  27. }
  28. }
  29.  
  30. Node* reverse(Node *head)
  31. {
  32. if(head == nullptr)
  33. return nullptr;
  34. Node *prev = nullptr;
  35. while(head->next != nullptr)
  36. {
  37. Node *next = head->next;
  38. head->next = prev;
  39. prev = head;
  40. head = next;
  41. }
  42. head->next = prev;
  43. return head;
  44. }
  45.  
  46. int main() {
  47. Node *list = nullptr;
  48. for (int i = 0; i < 4; ++i)
  49. list = push (list, i);
  50.  
  51. print (list);
  52. std::cout << std::endl;
  53. list = reverse (list);
  54. print (list);
  55. return 0;
  56. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
3 2 1 0 
0 1 2 3