fork download
  1. // Reverse a linked list using Recursion
  2. #include <iostream>
  3. using namespace std;
  4. struct Node {
  5. int data;
  6. struct Node* next;
  7. Node(int data)
  8. {
  9. this->data = data;
  10. next = NULL;
  11. }
  12. };
  13.  
  14. struct LinkedList {
  15. Node* head;
  16. LinkedList() { head = NULL; }
  17.  
  18. Node* reverse(Node* head)
  19. {
  20. if (head == NULL || head->next == NULL)
  21. return head;
  22. Node* rest = reverse(head->next);
  23. head->next->next = head;
  24. head->next = NULL;
  25. return rest;
  26. }
  27. void print()
  28. {
  29. struct Node* temp = head;
  30. while (temp != NULL) {
  31. cout << temp->data << " ";
  32. temp = temp->next;
  33. }
  34. }
  35. void push(int data)
  36. {
  37. Node* temp = new Node(data);
  38. temp->next = head;
  39. head = temp;
  40. }
  41. };
  42. int main()
  43. {
  44. LinkedList ll;
  45. ll.push(345);
  46. ll.push(89);
  47. ll.push(77);
  48. ll.push(65);
  49. cout << "Given linked list\n";
  50. ll.print();
  51. ll.head = ll.reverse(ll.head);
  52. cout << "\nReversed linked list \n";
  53. ll.print();
  54. return 0;
  55. }
  56. // mam iam just tried these programs as per the w3schools if i revised the previoous topics i can make it in efective way please provide the recording of week 2-2 session mam
  57.  
Success #stdin #stdout 0s 5300KB
stdin
Standard input is empty
stdout
Given linked list
65 77 89 345 
Reversed linked list 
345 89 77 65