stack c++
#include <bits/stdc++.h>
stack<int> stk;
stk.push(5);
int ans = stk.top(5); // ans =5
stk.pop();//removes 5
stack c++
#include <bits/stdc++.h>
stack<int> stk;
stk.push(5);
int ans = stk.top(5); // ans =5
stk.pop();//removes 5
stack c++
stack<int> stk;
stk.push(5);
int ans = stk.top(5); // ans =5
stk.pop();//removes 5
Basic stack implementation in c++
/* C++ program to implement basic stack
operations */
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000
class Stack {
int top;
public:
int a[MAX]; // Maximum size of Stack
Stack() { top = -1; }
bool push(int x);
int pop();
int peek();
bool isEmpty();
};
bool Stack::push(int x)
{
if (top >= (MAX - 1)) {
cout << "Stack Overflow";
return false;
}
else {
a[++top] = x;
cout << x << " pushed into stack\n";
return true;
}
}
int Stack::pop()
{
if (top < 0) {
cout << "Stack Underflow";
return 0;
}
else {
int x = a[top--];
return x;
}
}
int Stack::peek()
{
if (top < 0) {
cout << "Stack is Empty";
return 0;
}
else {
int x = a[top];
return x;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
// Driver program to test above functions
int main()
{
class Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stack\n";
//print all elements in stack :
cout<<"Elements present in stack : ";
while(!s.isEmpty())
{
// print top element in stack
cout<<s.peek()<<" ";
// remove top element in stack
s.pop();
}
return 0;
}
stack in c++
#include <iostream>
using namespace std;
#define M 100 //defined the size of the stack ;
//stack class for controlling
class STACK
{
int ara[M]; // declared an array for storing the stack elemenst
int top; // finding the top value
public:
//function for pushing values into the stack
STACK() // constructor for initializing
{
top = 0;
}
void push(int n)
{
if(top == M) // checking if the stack is full or not
{
cout << "Stack is full\n";
return;
}else // if the stack is not full, push the element
{
ara[top] = n;
top++;
}
}
//function for poping out elements from the stack or getting the elements
int pop()
{
if(top == 0)
{
cout << "Stack is empty\n";
return 0;
}else
{
top--;
return ara[top];
}
}
};
int main()
{
STACK stk1, stk2; //making two objects of type STACK
//pushing elements
for(int i = 0; i < 5; i++)
{
stk1.push(i);
stk2.push(i+1);
}
//poping elements
for(int i = 0; i < 5; i++)
{
cout << stk1.pop() << " ";
}
cout << "\n";
for(int i = 0; i < 5; i++)
{
cout << stk2.pop() << " ";
}
cout << "\n";
return 0;
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us