In: Computer Science
Suppose that two stacks of positive integers are needed for a project. Each stack is to contain integers that are less than or equal to 500. One stack is to contain even integers; the other stack is to contain odd integers. Also, the total number of values in the combined stacks at any given time will not exceed 200. ▪ Design a way to implement both stacks in only one(pay attention!!!) 1-D array. ▪ Write a Python class definition(s) for the double stack representation designed previously. Include the following operations: ◦ isEmpty (for each stack) ◦ size (for each stack) ◦ push (insert an integer onto the correct stack depending on whether it is even or odd) ◦ pop (for each stack) ◦ top (for each stack) ▪ Fully test all the stack operations in a Python main program.Note two stacks together should only use one array.
Solution :
#include<iostream>
#include<stdlib.h>
#define size 1000
using namespace std;
class twoStacks
{
int arr[size];
int top1, top2;
public:
twoStacks() // constructor
{
top1 = -1;
top2 = size;
}
// Method to push an element x to stack1
void push1(int x)
{
// There is at least one empty
space for new element
if (top1 < top2 - 1)
{
top1++;
arr[top1] = x;
}
else
{
cout
<< "Stack Overflow";
exit(1);
}
}
// Method to push an element x to stack2
void push2(int x)
{
// There is at least one empty
space for new element
if (top1 < top2 - 1)
{
top2--;
arr[top2] = x;
}
else
{
cout
<< "Stack Overflow";
exit(1);
}
}
// Method to pop an element from first stack
int pop1()
{
if (top1 >= 0 )
{
int x =
arr[top1];
top1--;
return
x;
}
else
{
cout
<< "Stack UnderFlow";
exit(1);
}
}
// Method to pop an element from second stack
int pop2()
{
if (top2 < size)
{
int x =
arr[top2];
top2++;
return
x;
}
else
{
cout
<< "Stack UnderFlow";
exit(1);
}
}
void print_stack1 ()
{
int i;
for (i = top1; i >= 0; --i)
{
printf ("%d ", arr[i]);
}
printf (" ");
}
void print_stack2 ()
{
int i;
for (i = top2; i < size; ++i)
{
printf ("%d ", arr[i]);
}
printf (" ");
}
};
/* Driver program to test twStacks class */
int main()
{
twoStacks st;
int num,choice=1;
while(choice==1)
{
cout <<"enter the
element";
cin >> num;
if(num%2==0)
st.push1(num);
else
st.push2(num);
cout<<"enter 1 to
enter other element in array ";
cin>>choice;
}
cout<<"content of stack 1 ";
st.print_stack1();
cout<<"content of stack 2 ";
st.print_stack2();
return 0;
}
Output :