fork download
  1. // C++ program for above approach
  2. #include <bits/stdc++.h>
  3. #include <iostream>
  4. using namespace std;
  5.  
  6. // Create a class Node to enter values and address in the
  7. // list
  8. class Node {
  9. public:
  10. int data;
  11. Node* next;
  12. Node(int x) {
  13. data = x;
  14. next = NULL;
  15. }
  16. };
  17.  
  18. // Function to reverse the linked list
  19. void reverseLL(Node** head)
  20. {
  21. // Create a stack "s" of Node type
  22. stack<Node*> s;
  23. Node* temp = *head;
  24. while (temp->next != NULL) {
  25. // Push all the nodes in to stack
  26. s.push(temp);
  27. temp = temp->next;
  28. }
  29. *head = temp;
  30. while (!s.empty()) {
  31. // Store the top value of stack in list
  32. temp->next = s.top();
  33. // Pop the value from stack
  34. s.pop();
  35. // update the next pointer in the list
  36. temp = temp->next;
  37. }
  38. temp->next = NULL;
  39. }
  40.  
  41. // Function to Display the elements in List
  42. void printlist(Node* temp)
  43. {
  44. while (temp != NULL) {
  45. cout << temp->data << " ";
  46. temp = temp->next;
  47. }
  48. }
  49.  
  50. // Program to insert back of the linked list
  51. void insert_back(Node** head, int value)
  52. {
  53.  
  54. // we have used insertion at back method to enter values
  55. // in the list.(eg: head->1->2->3->4->Null)
  56. Node* temp = new Node(value);
  57. temp->next = NULL;
  58.  
  59. // If *head equals to NULL
  60. if (*head == NULL) {
  61. *head = temp;
  62. return;
  63. }
  64. else {
  65. Node* last_node = *head;
  66. while (last_node->next != NULL)
  67. last_node = last_node->next;
  68. last_node->next = temp;
  69. return;
  70. }
  71. }
  72.  
  73. // Driver Code
  74. int main()
  75. {
  76. Node* head = NULL;
  77. insert_back(&head, 1);
  78. insert_back(&head, 2);
  79. insert_back(&head, 3);
  80. insert_back(&head, 4);
  81. cout << "Given linked list\n";
  82. printlist(head);
  83. reverseLL(&head);
  84. cout << "\nReversed linked list\n";
  85. printlist(head);
  86. return 0;
  87. }
  88.  
Success #stdin #stdout 0s 5292KB
stdin
1 2 3 4
stdout
Given linked list
1 2 3 4 
Reversed linked list
4 3 2 1