stack in two ways: 1. Using an array 2. Using the singly linked list class you i
ID: 3710764 • Letter: S
Question
stack in two ways:
1. Using an array
2. Using the singly linked list class you implemented before.
For each implementation define the following functions
1. function push that pushes a value onto the stack
2. function pop that pops a value off the stack
3. function Top that returns the top value of the stack without popping the stack
4. function isEmpty that determines if the stack is empty
5. function printStack that prints the stack Write a main (tester) that shows the usage of every function using different types (integers and strings at least)
Use Visual Studio C++
Explanation / Answer
Hi Dear,
Question is too long.
I have implemented stack using Array.
Please repost for Linked list implementation.
/* C++ program to implement basic stack
operations */
#include<iostream>
using namespace std;
#define MAX 1000
class Stack
{
int top;
public:
int a[MAX]; //Maximum size of Stack
Stack() { top = -1; }
bool push(int x);
int pop();
int Top();
bool isEmpty();
void printStack();
};
bool Stack::push(int x)
{
if (top >= MAX)
{
cout << "Stack Overflow";
return false;
}
else
{
a[++top] = x;
return true;
}
}
int Stack::pop()
{
if (top < 0)
{
cout << "Stack Underflow";
return 0;
}
else
{
int x = a[top--];
return x;
}
}
int Stack::Top()
{
if (top < 0)
{
cout << "Stack Underflow";
return 0;
}
else
{
return a[top];;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
void Stack::printStack()
{
if (top < 0)
{
cout << "Stack Underflow"<<endl;
}
else
{
int i = top;
while(i >= 0){
cout<<a[i]<<" ";
i--;
}
cout<<endl;
}
}
// Driver program to test above functions
int main()
{
struct Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stack ";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.