Hello, I have a difficulty in this question it is in my HW2 for Data Structures
ID: 3823457 • Letter: H
Question
Hello, I have a difficulty in this question it is in my HW2 for Data Structures course, Create a java class called DoubleStack to represent a double stack data structure it is like two stacks sharing the same array, one from the left side and the other one from the right side. However, this does not mean the array is divided equally between them. It depends on pop and push operations for each one of them. DoubleStack will have: isEmpty1(), size1(), push1(), top1(), pop2(), isEmpty2(), size2(), push2(), top2(), pop2(). write a main function to test them. Please help me to solve it, the due is tonight (midnight) Apr23rd, 17 11:59 pm
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
class DoubleStack
{
int data[], size, topIndex1, topIndex2;
public DoubleStack(int size)
{
//this.size = size;
data = new int[size];
topIndex1 = -1;
topIndex2 = size;
}
public void push1(int n)
{
if(topIndex1 < topIndex2 - 1)
{
topIndex1++;
data[topIndex1] = n;
System.out.println(" Elemnet is Pushed in Stack1 is:" +n);
}
else
{
System.out.println(" Stack Overflow");
System.exit(1);
}
}
public void push2(int n)
{
if(topIndex1 < topIndex2 - 1)
{
topIndex2--;
data[topIndex2] = n;
System.out.println(" Element is Pushed in Stack2 is:" +n);
}
else
{
System.out.println(" Stack Overflow");
System.exit(1);
}
}
public int pop1()
{
if(isEmpty1())
{
System.out.println(" Stack Underflow");
}
else
{
int n = data[topIndex1];
topIndex1--;
return n;
}
return 0;
}
public int pop2()
{
if(isEmpty2())
{
System.out.println(" Stack Underflow");
System.exit(1);
}
else
{
int n = data[topIndex2];
topIndex2++;
return n;
}
return 0;
}
public boolean isEmpty1()
{
if(topIndex1 == 0)
return true;
else
return false;
}
public boolean isEmpty2()
{
if(topIndex2 == size)
return true;
else
return false;
}
public static void main(String args[])
{
DoubleStack ds = new DoubleStack(5);
ds.push1(15);
ds.push2(40);
ds.push2(35);
ds.push1(24);
ds.push2(34);
while(!ds.isEmpty1())
{
System.out.print(" Popped Element is:" +ds.pop1());
}
while(!ds.isEmpty2())
{
System.out.print(" Popped Element is:" +ds.pop2());
}
}
}
OUTPUT
Elemnet is Pushed in Stack1 is:15
Element is Pushed in Stack2 is:40
Element is Pushed in Stack2 is:35
Elemnet is Pushed in Stack1 is:24
Element is Pushed in Stack2 is:34
Popped Element is :24
Popped Element is:34
Popped Element is:35
Popped Element is:40
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.