In: Computer Science
Implement a stack in C++ using an array, not an array list.
Make your stack size 5 when you test it, but do not hardcode this! You should be able to change the size for testing purposes with the change of one variable.
DO NOT use Stack class defined in C++
Implement the following methods in your stack class.
Write your own Driver file to show that you have implemented all the methods of the stack. A psuedocode example is listed below to guide you. Use print statements as well to show the popped elements, to show the stack after some pushes, to print the size of the stack.
Given below is the code and output. Please do rate the answer if it
helped. Thank you.
stack.h
--------
#ifndef STACK_H
#define STACK_H
#define STACK_SIZE 5
#include <iostream>
using namespace std;
template <typename T>
class Stack
{
private:
T data[STACK_SIZE];
int count;
public:
Stack(){
count = 0;
}
void push(T item){
if(!isFull())
data[count++] = item;
else
cout << "Stack is full. Can not push " << item <<
endl;
}
T pop(){
T dummy;
if(isEmpty()){
cout << "Stack empty. Can not pop!" << endl;
return dummy;
}
else{
return data[--count];
}
}
bool isEmpty(){
return count == 0;
}
bool isFull(){
return count == STACK_SIZE;
}
int size(){
return count;
}
void top(){
if(isEmpty()){
cout << "Stack empty" << endl;
}
else{
cout << "top = " << data[count-1] << endl;
}
}
void printStack(){
if(isEmpty()){
cout << "Stack empty" << endl;
}
else{
cout << endl << "Stack contents" << endl;
cout << data[count-1] << "<-top" <<
endl;
for(int i = count-2; i >= 0; i--)
cout << data[i] << endl;
}
cout << endl;
}
};
#endif
----
stacktest.cpp
------
#include <iostream>
#include "stack.h"
int main(){
Stack<string> shirts;
shirts.push("redShirt");
shirts.push("greenShirt");
shirts.push("yellowPants");
shirts.push("purpleSock");
shirts.push("pinkSocks");
shirts.printStack();
cout << "stack size = " << shirts.size() <<
endl;
shirts.push("blueShirt");
cout << "stack size = " << shirts.size() <<
endl;
cout << "popping " << shirts.pop() << endl;
cout << "popping " << shirts.pop() << endl;
cout << "stack size = " << shirts.size() <<
endl;
cout << "popping " << shirts.pop() << endl;
shirts.printStack();
shirts.top();
cout << "popping " << shirts.pop() << endl;
cout << "popping " << shirts.pop() << endl;
shirts.printStack();
cout << "stack size = " << shirts.size() <<
endl;
cout << "stack empty? " << shirts.isEmpty() <<
endl;
shirts.printStack();
return 0;
}