I am preparing for a test and have answered some questions dealing with stacks and queues the teacher has provided as samples. Could someone check over my work?
Code:
// stack.h – complete header file for Stack ADT
#include <iostream>
using namespace std;
class StackFull { /* Empty Exception Class */ };
class StackEmpty { /* Empty Exception Class */ };
class Stack // An array implementation of Stack ADT for storing integers
{
private:
int* ptr; // Holds address of dynamically-allocated integer array
int top; // Array index of top-most integer on the stack
int size; // Maximum number of integers that may be stored in the stack
public:
Stack(int num); // Dynamically allocate 1-D array of integers of size num
// and configure empty stack
~Stack(); // Deallocates stack array
void Push(int n); // Add integer n to the top of the stack if not full
// Otherwise, throw StackFull exception
int Pop(); // Removes top integer from stack AND returns value to
// client; throws StackEmpty exception if stack is empty
void MakeEmpty(); // Return stack to empty but usable state
bool IsFull() const; // Return true if stack is full; otherwise return false
bool IsEmpty() const; // Return true if stack is empty; otherwise return false
int Capacity() const; // Returns the maximum number of integers that may be
// stored in Stack object
}; // End Class Stack
1) Implement Stack.
Code:
Stack::Stack(int num)
{
ptr=new int[num];
top=0;
size=num;
}
2) Implement Push method
Code:
void Stack::Push(int n)
{
if(IsEmpty() )
throw StackFull();
else
{
ptr[top]=n;
top++;
}
}
3) Implement IsEmpty
Code:
bool Stack::IsEmpty() const
{
return (top == 0);
}
4) Implement Pop
Code:
int Stack::Pop()
{
if (IsEmpty())
throw StackEmpty();
else
{
int temp=ptr[top];
top--;
return temp;
}
}
5) Implement Desctructor
Code:
Stack::~Stack()
{
MakeEmpty();
}
6) Implement Capacity
Code:
int Stack::Capacity() const
{
return size;
}
7) Implement IsFull
Code:
bool Stack::IsFull() const
{
return (top == size);
}