Advertisement
STANAANDREY

stack using list

Jul 13th, 2023
1,074
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5.  
  6. struct ListNode {
  7.     struct ListNode *nxt;
  8.     int elem;
  9. };
  10.  
  11. class Stack {
  12. public:
  13.     Stack() {
  14.         stBuf = nullptr;
  15.     }
  16.  
  17.     void push(int elem) {
  18.         ListNode *newLN = (ListNode*)malloc(sizeof(ListNode));
  19.         if (newLN == nullptr) {
  20.             perror("");
  21.             _free();
  22.             exit(1);
  23.         }
  24.         newLN->elem = elem;
  25.         newLN->nxt = stBuf;
  26.         stBuf = newLN;
  27.         size++;
  28.     }
  29.  
  30.     int getSize() {
  31.         return size;
  32.     }
  33.  
  34.     int getTop() {
  35.         return stBuf->elem;
  36.     }
  37.  
  38.     int pop() {
  39.         if (!size) {
  40.             exit(-1);
  41.         }
  42.         ListNode *topElem = stBuf;
  43.         int elem = stBuf->elem;
  44.         stBuf = topElem->nxt;
  45.         free(topElem);
  46.         size--;
  47.         return elem;
  48.     }
  49.  
  50.     ~Stack() {
  51.         _free();
  52.     }
  53.  
  54. private:
  55.     ListNode *stBuf;
  56.     int size = 0;
  57.  
  58.     void _free() {
  59.         while (size) {
  60.             pop();
  61.         }
  62.     }
  63. };
  64.  
  65. int main() {
  66.     using std::cout;
  67.     using std::endl;
  68.     Stack st;
  69.     st.push(2);
  70.     st.push(4);
  71.     st.pop();
  72.     cout << st.getSize() <<  ' ' << st.getTop() << endl;
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement