Last active
August 26, 2019 16:32
-
-
Save jkotra/aa76f13fce1e39f4b53dc2188726d57e to your computer and use it in GitHub Desktop.
Stack in C++
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
/*Stack in c++ | |
*(FOR RECORD WORK) | |
*Jagadeesh Kotra (github.com/jkotra) | |
*Dt: 26.08.2019 */ | |
#include <iostream> | |
using namespace std; | |
class Stack{ | |
private: | |
int stk[5]{}; | |
const int maxsize = 5; | |
int top; | |
public: | |
Stack(); | |
void push(int x); | |
void pop(); | |
bool isempty(); | |
bool isfull(); | |
void gettop(); | |
}; | |
Stack::Stack() { | |
top = -1; | |
} | |
void Stack::push(int x) { | |
if (isfull()) | |
cout << "stack Overflow" << endl; | |
else { | |
top++; | |
stk[top] = x; | |
} | |
} | |
void Stack::pop() { | |
if (isempty()) | |
cout << "stack underflow" << endl; | |
else { | |
cout << stk[top] << " popped" << endl; | |
top--; | |
} | |
} | |
bool Stack::isempty() { | |
return top == -1; | |
} | |
bool Stack::isfull() { | |
return top == (maxsize-1); | |
} | |
void Stack::gettop() { | |
if (isempty()) | |
cout << "Stack is empty!"; | |
else | |
cout << "top most element is " << stk[top] << endl; | |
} | |
int main() { | |
Stack s; | |
s.push(1); | |
s.push(2); | |
s.push(3); | |
s.push(4); | |
s.pop(); | |
s.gettop(); | |
s.pop(); | |
s.gettop(); | |
return 0; | |
} | |
/* Output : | |
* 4 popped | |
* top most element is 3 | |
* 3 popped | |
* top most element is 2 */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment