In: Computer Science
C++ Please
Fill in for the functions for the code below. The functions will be implemented using vectors ONLY. 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:
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() {// ... }
};
Here I have implemented the code: Stack using vectos (CPP)
Change it as you like and test it.
#include<iostream>
#include<vector>
using namespace std;
class Stack
{
private:
int maxSize;
vector < int >v;
int top;
public:
Stack (int size)
{
this->maxSize = size;
this->v.reserve (this->maxSize);
this->top = -1;
}
void push (int j)
{
if (!(this->isFull ()))
{
this->v[++this->top] = j;
}
else
{
cout << "stack is full" << endl;
}
}
int pop ()
{
if (!(this->isEmpty ()))
{
cout<<this->v[this->top--] <<endl;
}
else
{
cout << "\nstack is empty" << endl;
cout << "StackOverflow " << endl;
}
}
int peak ()
{
return this->v[this->top];
}
bool isEmpty ()
{
return (this->top == -1);
}
bool isFull ()
{
return (this->top == this->maxSize - 1);
}
};
int
main ()
{
Stack *ptr = new Stack(15);
ptr->push (5);
ptr->push (7);
ptr->push (9);
int pop1 = ptr->pop ();
int pop2 = ptr->pop ();
bool isEmpty = ptr->isEmpty();
}