fork download
  1. // Reverse a linked list by Iterative Method
  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. struct LinkedList {
  14. Node* head;
  15. LinkedList() { head = NULL; }
  16. void reverse()
  17. {
  18. Node* current = head;
  19. Node *prev = NULL, *next = NULL;
  20. while (current != NULL) {
  21. next = current->next;
  22. current->next = prev;
  23. prev = current;
  24. current = next;
  25. }
  26. head = prev;
  27. }
  28. void print()
  29. {
  30. struct Node* temp = head;
  31. while (temp != NULL) {
  32. cout << temp->data << " ";
  33. temp = temp->next;
  34. }
  35. }
  36. void push(int data)
  37. {
  38. Node* temp = new Node(data);
  39. temp->next = head;
  40. head = temp;
  41. }
  42. };
  43. int main()
  44. {
  45. LinkedList ll;
  46. ll.push(345);
  47. ll.push(89);
  48. ll.push(77);
  49. ll.push(65);
  50. cout << "Given linked list\n";
  51. ll.print();
  52. ll.reverse();
  53. cout << "\nReversed linked list \n";
  54. ll.print();
  55. return 0;
  56. }
  57. // 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
  58.  
Success #stdin #stdout 0s 5264KB
stdin
Standard input is empty
stdout
Given linked list
65 77 89 345 
Reversed linked list 
345 89 77 65