Advertisement
193030

Reverse linked list

Aug 9th, 2021
950
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct Node
  6. {
  7.     int data;
  8.     struct Node* next;
  9. } *first = NULL;
  10.  
  11.  
  12. void add(int data)
  13. {
  14.     if(first == NULL)
  15.     {
  16.         first = new struct Node;
  17.         first->data = data;
  18.         first->next = NULL;
  19.         return;
  20.     }
  21.     struct Node* p = first;
  22.     while(p->next)
  23.     {
  24.         p = p->next;
  25.     }
  26.    
  27.     struct Node* t = new struct Node;
  28.     p->next = t;
  29.     t->data = data;
  30.     t->next = NULL;
  31.    
  32. }
  33.  
  34. void display(struct Node *p)
  35. {
  36.     while(p)
  37.     {
  38.         cout << p->data << endl;
  39.         p = p->next;
  40.     }
  41. }
  42.  
  43. void reverseLL(struct Node*q, struct Node*p )
  44. {
  45.     if (p)
  46.     {
  47.         reverseLL(p, p->next);
  48.         p->next = q;
  49.     }
  50.     else
  51.         first = q;
  52. }
  53.  
  54.  
  55.  
  56. int main()
  57. {
  58.     add(10), add(20), add(30);
  59.     display(first);
  60.     reverseLL(NULL, first);
  61.     display(first);
  62.  
  63. }
Advertisement
RAW Paste Data Copied
Advertisement