Explain how to implement two stacks in one array A[1..n] in such a way that neither stack overflows unless the total number of elements in both stacks together is n. The PUSH and POP operations should run in O(1) time.
PLEASE READ: Do not code unless the question asks for it, then code in java. Importantly and clearly answer the question by explaining with words fully first, thank you
Answer:
->The purpose is to start two stacks from two extreme corners of arr[]/stack1 starts from the leftmost element, the first element in stack1 is pushed at index 0.
->The stack2 starts from the rightmost corner, the first element in stack2 is pushed at index(n-1). Both stacks grow in opposite direction.
->To check for overflow, all we need to check is for space between top elements of both stacks. This check is highlighted in the below code:
Programming Code:
import java.io.*;
import java.util.*;
class twoStacks
{
int *arr;
int size;
int tops1,top2;
public:
twoStacks(int n) //constructor
{
size=n;
arr= new int[n];
top1=-1;
top2= size;
}
//Method to push an element x to stack1
void push(intx)
{
//There is atleast one empty space for new element
if(top1<top2-1)
{
top1++;
arr[top1]=x;
}
else
{
System.out.println("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
{
System.out.println("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
{
System.out.println("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
{
System.out.println("Stack underFlow");
exit(1);
}
}
}
Step by step
Solved in 3 steps