fork download
  1. // Reverse a linked list using Stack
  2. #include <iostream>
  3. #include <stack>
  4. using namespace std;
  5. class Node {
  6. public:
  7. int data;
  8. Node* next;
  9. Node(int x) {
  10. data = x;
  11. next = NULL;
  12. }
  13. };
  14. void reverseLL(Node** head)
  15. {
  16. stack<Node*> s;
  17. Node* temp = *head;
  18. while (temp->next != NULL) {
  19. // Push all the nodes in to stack
  20. s.push(temp);
  21. temp = temp->next;
  22. }
  23. *head = temp;
  24. while (!s.empty()) {
  25. temp->next = s.top();
  26. s.pop();
  27. temp = temp->next;
  28. }
  29. temp->next = NULL;
  30. }
  31. void printlist(Node* temp)
  32. {
  33. while (temp != NULL) {
  34. cout << temp->data << " ";
  35. temp = temp->next;
  36. }
  37. }
  38. void insert_back(Node** head, int value)
  39. {
  40. Node* temp = new Node(value);
  41. temp->next = NULL;
  42. if (*head == NULL) {
  43. *head = temp;
  44. return;
  45. }
  46. else {
  47. Node* last_node = *head;
  48. while (last_node->next != NULL)
  49. last_node = last_node->next;
  50. last_node->next = temp;
  51. return;
  52. }
  53. }
  54. int main()
  55. {
  56. Node* head = NULL;
  57. insert_back(&head, 347);
  58. insert_back(&head, 247);
  59. insert_back(&head, 147);
  60. insert_back(&head, 47);
  61. insert_back(&head, 4);
  62. cout << "Given linked list\n";
  63. printlist(head);
  64. reverseLL(&head);
  65. cout << "\nReversed linked list\n";
  66. printlist(head);
  67. return 0;
  68. }
  69. // 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 5296KB
stdin
Standard input is empty
stdout
Given linked list
347 247 147 47 4 
Reversed linked list
4 47 147 247 347