Created
May 3, 2017 15:59
-
-
Save tornikegomareli/651c7d521977572640e7e37f0b33449e to your computer and use it in GitHub Desktop.
Data Structures : Stack Implementation
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; | |
| class Stack | |
| { | |
| private: | |
| int *node; | |
| int top, length; | |
| public: | |
| Stack(int = 0); | |
| ~Stack(); | |
| void push(int); | |
| int pop(); | |
| void display(); | |
| }; | |
| Stack::Stack(int size) | |
| { | |
| top = -1; | |
| length = size; | |
| if (size == 0) | |
| node = 0; | |
| else | |
| node = new int[length]; | |
| } | |
| Stack::~Stack() | |
| { | |
| if (node != 0) | |
| delete[] node; | |
| } | |
| void Stack::push(int elem) | |
| { | |
| if (node == 0) //If the stack size is zero, allow user to mention it at runtime | |
| { | |
| cout << "Stack of zero size" << endl; | |
| cout << "Enter a size for stack : "; | |
| cin >> length; | |
| node = new int[length]; | |
| } | |
| if (top == (length - 1)) //If the top reaches to the maximum stack size | |
| { | |
| cout << "\nCannot push " << elem << ", Stack full" << endl; | |
| return; | |
| } | |
| else | |
| { | |
| top++; | |
| node[top] = elem; | |
| } | |
| } | |
| int Stack::pop() | |
| { | |
| if (node == 0 || top == -1) | |
| { | |
| cout << "Stack empty!"; | |
| return -1; | |
| } | |
| int ret = node[top]; | |
| top--; | |
| return ret; | |
| } | |
| void Stack::display() | |
| { | |
| for (int i = 0; i <= top; i++) | |
| cout << node[i] << " "; | |
| cout << endl; | |
| } | |
| int main() | |
| { | |
| Stack stack; | |
| for (size_t i = 0; i < 30; i++) | |
| { | |
| stack.push(i); | |
| } | |
| for (size_t i = 0; i < 20; i++) | |
| { | |
| stack.display(); | |
| } | |
| cout << endl; | |
| for (size_t i = 0; i < 20; i++) | |
| { | |
| stack.pop(); | |
| stack.display(); | |
| } | |
| cin.get(); | |
| cin.get(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment