nezvers

C++ Single link list (push/ pop/ reverse)

Aug 28th, 2020 (edited)
2,656
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.11 KB | None | 0 0
  1. /*
  2. Github: https://github.com/nezvers
  3. Youtube: https://www.youtube.com/channel/UCb4-Y0E6mmwjtawcitIAzKQ
  4. Twitter: https://twitter.com/NeZversStudio
  5. */
  6.  
  7. #include <iostream>
  8.  
  9. using namespace std;
  10.  
  11. typedef struct SLNode
  12. {
  13.     int data;
  14.     SLNode *next = nullptr;
  15.     SLNode(int _data, SLNode *_next)
  16.     {
  17.         data = _data;
  18.         next = _next;
  19.     }
  20. }SLNode;
  21.  
  22. class SingleLinkList
  23. {
  24. public:
  25.     SingleLinkList(): head(nullptr){cout << "List initialized" << endl;}
  26.     void push(int _data)
  27.     {
  28.         SLNode *node = new SLNode(_data, head);
  29.         head = node;
  30.         cout << "Push data: " << node->data << endl;
  31.     }
  32.     void pop()
  33.     {
  34.         SLNode *temp = head;
  35.         head = head->next;
  36.         cout << "Pop: " << temp->data << endl;
  37.         delete temp;
  38.     }
  39.     void print_data()
  40.     {
  41.         SLNode *temp = head;
  42.         while (temp != NULL)
  43.         {
  44.             cout << "Print: " << temp->data << endl;
  45.             temp = temp->next;
  46.         }
  47.     }
  48.     void reverse_data()
  49.     {
  50.         cout << "Reversing data " << endl;
  51.         SLNode *prev = nullptr;
  52.         SLNode *current = head;
  53.         SLNode *next = nullptr;
  54.  
  55.         while (current != NULL)
  56.         {
  57.             next = current->next;
  58.             current->next = prev;
  59.             prev = current;
  60.             current = next;
  61.         }
  62.         head = prev;
  63.     }
  64.     ~SingleLinkList()
  65.     {
  66.         cout << "Deleting data pointers" << endl;
  67.         if (head != NULL)
  68.         {
  69.             while (head != NULL)
  70.             {
  71.                 pop();
  72.             }
  73.         }
  74.     }
  75. private:
  76.     SLNode *head;
  77. };
  78.  
  79. int main()
  80. {
  81.     SingleLinkList MyList = SingleLinkList();
  82.     MyList.push(9);
  83.     MyList.push(4);
  84.     MyList.push(7);
  85.     MyList.push(6);
  86.     MyList.push(1);
  87.     MyList.push(3);
  88.     MyList.push(8);
  89.     MyList.push(2);
  90.     MyList.push(5);
  91.     MyList.print_data();
  92.     MyList.reverse_data();
  93.     MyList.print_data();
  94.  
  95.     MyList.pop();
  96.     MyList.pop();
  97.     MyList.pop();
  98.     MyList.pop();
  99.     MyList.print_data();
  100.  
  101.     cout << "Hello world!" << endl;
  102.     return 0;
  103. }
  104.  
Add Comment
Please, Sign In to add comment