Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- #include <stdlib.h>
- struct ListNode {
- struct ListNode *nxt;
- int elem;
- };
- class Stack {
- public:
- Stack() {
- stBuf = nullptr;
- }
- void push(int elem) {
- ListNode *newLN = (ListNode*)malloc(sizeof(ListNode));
- if (newLN == nullptr) {
- perror("");
- _free();
- exit(1);
- }
- newLN->elem = elem;
- newLN->nxt = stBuf;
- stBuf = newLN;
- size++;
- }
- int getSize() {
- return size;
- }
- int getTop() {
- return stBuf->elem;
- }
- int pop() {
- if (!size) {
- exit(-1);
- }
- ListNode *topElem = stBuf;
- int elem = stBuf->elem;
- stBuf = topElem->nxt;
- free(topElem);
- size--;
- return elem;
- }
- ~Stack() {
- _free();
- }
- private:
- ListNode *stBuf;
- int size = 0;
- void _free() {
- while (size) {
- pop();
- }
- }
- };
- int main() {
- using std::cout;
- using std::endl;
- Stack st;
- st.push(2);
- st.push(4);
- st.pop();
- cout << st.getSize() << ' ' << st.getTop() << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement