I need help with the following C programming Stack class, I need to complete the
ID: 3872918 • Letter: I
Question
I need help with the following C programming Stack class, I need to complete the C skeleton code:
Write the C code for a stack class, and test it to be sure it is working correctly.
Given the API for a (fixed size), floating point stack class, write the code to create a stack class (in C):
IMPORTANT: You must use the GIVEN API code below with the given variable names. It must be a class called 'float_stack' NOT a struct.
// START CODE BELOW:
class float_stack {
public:
float_stack();
size_t size() const;
bool empty() const;
float peek() const;
void pop();
void push(float value);
friend std::ostream& operator<<(std::ostream& os, const float_stack& st);
private:
void check_empty() const; // exit if true (throw exception in C++)
void check_overflow() const; // ditto
private:
static const size_t maxStack_ = 30;
size_t size_;
float data_[maxStack_];
};
Explanation / Answer
#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();
bool isEmpty();
};
bool Stack::push(int x)
{
if (top >= MAX)
{
cout << "Stack Overflow";
return false;
}
else
{
a[++top] = x;
return true;
}
}
int Stack::pop()
{
if (top < 0)
{
cout << "Stack Underflow";
return 0;
}
else
{
int x = a[top--];
return x;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
// Driver program to test above functions
int main()
{
struct Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stack ";
return 0;
}