In: Computer Science
C++ Please
Fill in for the functions for the code below. The functions will be implemented using vectors. Additional public helper functions or private members/functions can be used. The List class will be instantiated via a pointer and called similar to the code below:
---the code can be general (can be tested with any int main() test function)---
Stack *ptr = new Stack();
ptr->push(value);
int pop1 = ptr->pop();
int pop2 = ptr->pop();
bool isEmpty = ptr->empty();
class Stack{
public:
// Default Constructor
Stack() {// ... }
// Push integer n onto top of stack
void push(int n) {// ... }
// Pop element on top of stack
int pop() {// ... }
// Get the top element but do not pop it (peek at top of stack)
int top() {// ... }
// Return whether the stack is empty or not
bool empty() {// ... }
};
#include <iostream>
#include<vector>
using namespace std;
const int MAXSIZE=5; //Define max size of stack vector
class Stack{
int tp; //top of stack
vector<int> v; //vector
public:
// Default Constructor
Stack()
{
tp=-1;
v.reserve(MAXSIZE);
}
// Push integer n onto top of stack
void push(int n)
{
if(full())
{
cout<<"Stack Overflow"<<endl;
}
else {
v[++tp]=n; //if not full, element is inserted
}
}
// Pop element on top of stack
int pop()
{
if(!empty())
{
return(v[tp--]); // if not empty, top element is popped
}
else
{
cout<<"underflow"<<endl;
}
}
// Get the top element but do not pop it (peek at top of stack)
int top()
{
if(!empty())
return(v[tp]); //if not empty, return top
}
// Return whether the stack is empty or not
bool empty()
{
return(tp==-1); //if top==-1, the true is returned, else FALSE
}
bool full()
{
return(tp==(MAXSIZE-1)); //if full, true is returned, else FALSE
}
void display()
{
if(!empty())
{
cout<<endl<<"Stack elements are:";
for(int i=tp; i>=0; i--)
cout<<v[i]<<" ";
cout<<endl;
}
else
cout<<"Stack is empty"<<endl;
}
};
int main()
{
int ch, val;
Stack *ptr=new Stack();
do {
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) check stack empty"<<endl;
cout<<"5) check stack full"<<endl;
cout<<"6) get stack top"<<endl;
cout<<"7) Exit"<<endl;
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
ptr->push(val);
break;
}
case 2: {
if(!ptr->empty())
{
int pop1=ptr->pop();
cout<<"popped element is::"<<pop1<<endl;
}
else
cout<<"underflow"<<endl;
break;
}
case 3: {
ptr->display();
break;
}
case 4: {
if(ptr->empty())
cout<<"stack empty"<<endl;
else
cout<<"stack not empty"<<endl;
break;
}
case 5: {
if(ptr->full())
cout<<"stack Full"<<endl;
else
cout<<"stack not Full"<<endl;
}
break;
case 6: {
if(!ptr->empty())
cout<<"Stack top is"<<ptr->top()<<endl;
else
cout<<"stack empty"<<endl;
break;
}
case 7: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=7);
return 0;
}