fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // creating node
  5. struct Node {
  6. int data;
  7. struct Node* next;
  8. Node(int data)
  9. {
  10. this->data = data;
  11. next = NULL;
  12. }
  13. };
  14.  
  15. struct LinkedList {
  16. Node* head;
  17. LinkedList() { head = NULL; }
  18.  
  19. // created a function to reverse a linked list
  20. void reverse()
  21. {
  22. // we are Initializing current, previous and next pointers
  23. Node* current = head;
  24. Node *prev = NULL, *next = NULL;
  25.  
  26. while (current != NULL) {
  27. next = current->next;
  28. current->next = prev;
  29. prev = current;
  30. current = next;
  31. }
  32. head = prev;
  33. }
  34.  
  35. // now created a function to print the output
  36. void print()
  37. {
  38. struct Node* temp = head;
  39. while (temp != NULL) {
  40. cout << temp->data << " ";
  41. temp = temp->next;
  42. }
  43. }
  44.  
  45. void push(int data)
  46. {
  47. Node* temp = new Node(data);
  48. temp->next = head;
  49. head = temp;
  50. }
  51. };
  52.  
  53. int main()
  54. {
  55. LinkedList ab;
  56. ab.push(5);
  57. ab.push(10);
  58. ab.push(15);
  59. ab.push(25);
  60.  
  61. cout << "Given linked list is :\n";
  62. ab.print();
  63.  
  64. ab.reverse();
  65.  
  66. cout << "\nReversed linked list is : \n";
  67. ab.print();
  68. return 0;
  69. }
  70.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Given linked list is :
25 15 10 5 
Reversed linked list is : 
5 10 15 25