c++ 1. Make the following changes to the stack class: Make all necessary changes
ID: 3578428 • Letter: C
Question
c++
1. Make the following changes to the stack class:
Make all necessary changes to have the class store integers on the stack instead of characters. pop should return -1 if called when the stack is empty.
Add a print member function that prints the values in the stack from top to bottom, one per line. print should not change the stack.
Write an elements member function that returns the number of elements on the stack. elements should not print anything. elements should not change the stack.
Write a peek member function that returns the top element on the stack. peek returns -1 if the stack is empty. peek should not change the stack.
Explanation / Answer
#include <iostream>
#include <stdlib.h>
using namespace std;
const int stack_size = 100;
class stack
{
private:
int data [stack_size]; // elements in the stack
int top; // index of the top element of the stack
public:
stack (); // constructor creates an empty stack
void push (int item); // adds an element to the top of the stack
int pop (); // removes and returns the top element
bool empty (); // returns true if stack is empty
bool full (); // returns true if stack is full
void print(); //print stack values from top to bottom
int elements(); //return number of elements
int peek(); //return top element
};
// constructor creates an empty stack
stack::stack ()
{
top = -1;
}
// push adds an element, item, to the top of the stack
void stack::push (int item)
{
// if the stack is full, print an error message
if (full ())
{
cout << " Stack Class Error: Pushing on a full stack";
cout << " Element being pushed is " << item;
}
else // OK to push the new element
{
top++;
data [top] = item;
}
}
// pop removes and returns the top element from the stack
int stack::pop ()
{
// if the stack is empty, print an error message
if (empty ())
{
cout << " Stack Class Error: Popping an empty stack";
cout << " Returning a ?";
return -1;
}
else // OK to pop the stack
{
top--;
return data [top + 1];
}
}
// empty returns true if the stack is empty, else it returns false
bool stack::empty ()
{
return top == -1;
}
// full returns true if the stack is full, else it returns false
bool stack::full ()
{
return top == stack_size - 1;
}
void stack::print ()
{
for(int i=top;i>=0;i--)
cout << data[i]<<endl;
}
int stack::elements ()
{
return top+1;
}
int stack::peek ()
{
return data[top];
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.