fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long int
  4.  
  5. class Node {
  6. public:
  7. int data;
  8. Node * next;
  9.  
  10. Node(int new_data) {
  11. data = new_data;
  12. next = nullptr;
  13. }
  14. };
  15.  
  16. Node *reverseList(Node *head) {
  17.  
  18. Node *curr = head, *prev = nullptr, *next;
  19.  
  20. // Traverse all the nodes of Linked List
  21. while (curr != nullptr) {
  22.  
  23. // Store next
  24. next = curr->next;
  25.  
  26. // Reverse current node's next pointer
  27. curr->next = prev;
  28.  
  29. // Move pointers one position ahead
  30. prev = curr;
  31. curr = next;
  32. }
  33.  
  34. return prev;
  35. }
  36.  
  37. void printList(Node *node) {
  38. while (node != nullptr) {
  39. cout << node->data;
  40. if (node->next)
  41. cout << " -> ";
  42. node = node->next;
  43. }
  44. }
  45.  
  46. int main() {
  47.  
  48. Node *head = new Node(1);
  49. head->next = new Node(2);
  50. head->next->next = new Node(3);
  51. head->next->next->next = new Node(4);
  52. head->next->next->next->next = new Node(5);
  53.  
  54. head = reverseList(head);
  55.  
  56. printList(head);
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
5 -> 4 -> 3 -> 2 -> 1