Created
January 8, 2026 14:37
-
-
Save m1irka/43c3a4d8a2ec04adf5402bcc79092e9e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| using namespace std; | |
| template <typename T> | |
| class Stack { | |
| private: | |
| class Node { | |
| public: | |
| T data; | |
| Node* next; | |
| Node(const T& value, Node* n = nullptr) : data(value), next(n) {} | |
| }; | |
| Node* head; | |
| size_t count; | |
| public: | |
| Stack() : head(nullptr), count(0) {} | |
| ~Stack() { clear(); } | |
| void push(const T& value) { | |
| head = new Node(value, head); | |
| ++count; | |
| } | |
| void pop() { | |
| if (empty()) { | |
| cout << "Stack is empty!" << endl; | |
| return; | |
| } | |
| Node* temp = head; | |
| head = head->next; | |
| delete temp; | |
| --count; | |
| } | |
| T top() const { | |
| if (empty()) { | |
| throw runtime_error("Stack is empty!"); | |
| } | |
| return head->data; | |
| } | |
| bool empty() const { return count == 0; } | |
| size_t size() const { return count; } | |
| void clear() { | |
| while (!empty()) { | |
| pop(); | |
| } | |
| } | |
| void print() const { | |
| Node* temp = head; | |
| cout << "( "; | |
| while (temp) { | |
| cout << temp->data; | |
| if (temp->next) cout << ", "; | |
| temp = temp->next; | |
| } | |
| cout << " )" << endl; | |
| } | |
| }; | |
| int main() { | |
| Stack<int> st; | |
| st.push(10); | |
| st.push(20); | |
| st.push(30); | |
| cout << "Stack: "; | |
| st.print(); | |
| cout << "Top: " << st.top() << endl; | |
| cout << "Size: " << st.size() << endl; | |
| st.pop(); | |
| cout << "After pop: "; | |
| st.print(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment