Answer to Question #263359 in C++ for devi

Question #263359


Implement a Stack to store a character in the node. Implement the following operations

push, pop and peek:.

void push (char c);

char pop();

char peek();

int isEmpty();

void printStack();



1
Expert's answer
2021-11-09T17:46:13-0500
#include <bits/stdc++.h>
using namespace std;
 
#define SIZE 100
 
class stack
{
    int *arr;
    int top;
    int capacity;
 
public:
    stack(int size = SIZE);       
    ~stack();                       
 
    void push(int);
    int pop();
    int peek();
 
    int size();
    bool isEmpty();
    bool isFull();
};
 
stack::stack(int size)
{
    arr = new int[size];
    capacity = size;
    top = -1;
}


stack::~stack() {
    delete[] arr;
}
 


void stack::push(int x)
{
    if (isFull())
    {
        exit(EXIT_FAILURE);
    }
 
    cout << "Insert " << x << endl;
    arr[++top] = x;
}
 
int stack::pop()
{


    if (isEmpty())
    {
        exit(EXIT_FAILURE);
    }
 
    cout << "Remove " << peek() << endl;
 
    return arr[top--];
}
 
int stack::peek()
{
    if (!isEmpty()) {
        return arr[top];
    }
    else {
        exit(EXIT_FAILURE);
    }
}
 
bool stack::isEmpty() {
    return top == -1;               
}
 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS