fork download
  1. // Reverse a linked list by Tail Recursive Method
  2. #include <iostream>
  3. using namespace std;
  4. struct Node {
  5. int data;
  6. struct Node* next;
  7. Node(int x) {
  8. data = x;
  9. next = NULL;
  10. }
  11. };
  12. void reverseUtil(Node* curr, Node* prev, Node** head);
  13. void reverse(Node** head)
  14. {
  15. if (!head)
  16. return;
  17. reverseUtil(*head, NULL, head);
  18. }
  19. void reverseUtil(Node* curr, Node* prev, Node** head)
  20. {
  21. if (!curr->next) {
  22. *head = curr;
  23. curr->next = prev;
  24. return;
  25. }
  26. Node* next = curr->next;
  27. curr->next = prev;
  28. reverseUtil(next, curr, head);
  29. }
  30. void printlist(Node* head)
  31. {
  32. while (head != NULL) {
  33. cout << head->data << " ";
  34. head = head->next;
  35. }
  36. cout << endl;
  37. }
  38. int main()
  39. {
  40. Node* head1 = new Node(8);
  41. head1->next = new Node(7);
  42. head1->next->next = new Node(6);
  43. head1->next->next->next = new Node(5);
  44. head1->next->next->next->next = new Node(4);
  45. head1->next->next->next->next->next = new Node(3);
  46. head1->next->next->next->next->next->next = new Node(2);
  47. head1->next->next->next->next->next->next->next= new Node(1);
  48. cout << "Given linked list\n";
  49. printlist(head1);
  50. reverse(&head1);
  51. cout << "Reversed linked list\n";
  52. printlist(head1);
  53. return 0;
  54. }
  55. // 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
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
Given linked list
8 7 6 5 4 3 2 1 
Reversed linked list
1 2 3 4 5 6 7 8