fork download
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. class Node {
  5. public:
  6. int data;
  7. Node* next; //this pointer, will store the address of the next node
  8. Node* prev;
  9. Node(int val) {
  10. data = val;
  11. next = NULL; //NULL means nothing, not pointing to anything
  12. }
  13. };
  14.  
  15. Node* revLL(Node* head) {
  16. // Initializing three pointers
  17. Node* prev = NULL;
  18. Node* curr = head;
  19. Node* next = NULL;
  20.  
  21. // Iterating through the linked list
  22. while (curr != NULL) {
  23. // Storing the next node
  24. next = curr->next;
  25. // Updating the next pointer of curr to prev
  26. curr->next = prev;
  27. // Updating prev as curr and curr as next
  28. prev = curr;
  29. curr = next;
  30. }
  31.  
  32. // prev now points to the new head of the reversed list
  33. return prev;
  34. }
  35.  
  36. void printLL(Node* node) {
  37.  
  38. while (node != NULL) {
  39. // So I print the current node value
  40. cout << node->data <<" ";
  41. // Then I move to the next node
  42. node = node->next;
  43. }
  44. cout<<endl;
  45. }
  46.  
  47. void AddAtEnd(Node* head, int val){
  48. //I want to add a new node, at the end of my LL
  49.  
  50.  
  51. // Create a new node
  52. Node* newNode = new Node(val);
  53.  
  54. // Go to the last node
  55. Node* curr = head;
  56. while(curr->next != NULL) { // because the last element's next will be NULL
  57. curr = curr->next;
  58. }
  59.  
  60. // Now, It is pointing to the last element
  61. // Point the next of the last node to new node.
  62.  
  63. curr->next = newNode;
  64. }
  65.  
  66. int main() {
  67. Node* head = new Node(1);
  68. // head->next = new Node(2);
  69. // head->next->next = new Node(3);
  70. // head->next->next->next = new Node(4);
  71.  
  72. AddAtEnd(head, 2);
  73. AddAtEnd(head, 3);
  74. AddAtEnd(head, 4);
  75. AddAtEnd(head, 5);
  76. AddAtEnd(head, 6);
  77.  
  78. cout << "Given linked list: ";
  79. printLL(head);
  80.  
  81. head = revLL(head);
  82.  
  83. cout << "Reversed linked list: ";
  84. printLL(head);
  85.  
  86. return 0;
  87. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
Given linked list: 1 2 3 4 5 6 
Reversed linked list: 6 5 4 3 2 1