0% found this document useful (0 votes)
7 views2 pages

Assigsnment 1 B

Assignment 1b

Uploaded by

randomclips7672
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Assigsnment 1 B

Assignment 1b

Uploaded by

randomclips7672
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

2. Create a data structure two Stacks that represents two stacks.

Implementation of
two Stacks should use only one array, i.e., both stacks should use the same array
for storing elements. Following functions must be supported by two Stacks.

public class TwoStacks {


private int[] array;
private int top1;
private int top2;
private int size1;
private int size2;

public TwoStacks(int capacity) {


array = new int[capacity];
top1 = -1;
top2 = capacity;
size1 = 0;
size2 = 0;
}

// Push element to stack 1


public void push1(int x) {
if (top1 < top2 - 1) {
top1++;
array[top1] = x;
size1++;
} else {
System.out.println("Stack 1 is full. Cannot push element.");
}
}

// Push element to stack 2


public void push2(int x) {
if (top2 > top1 + 1) {
top2--;
array[top2] = x;
size2++;
} else {
System.out.println("Stack 2 is full. Cannot push element.");
}
}

// Pop element from stack 1


public int pop1() {
if (top1 >= 0) {
int popped = array[top1];
top1--;
size1--;
return popped;
} else {
System.out.println("Stack 1 is empty.");
return -1;
}
}

// Pop element from stack 2


public int pop2() {
if (top2 < array.length) {
int popped = array[top2];
top2++;
size2--;
return popped;
} else {
System.out.println("Stack 2 is empty.");
return -1;
}
}

public static void main(String[] args) {


TwoStacks twoStacks = new TwoStacks(6);

twoStacks.push1(10);
twoStacks.push1(20);
twoStacks.push2(30);
twoStacks.push2(40);
twoStacks.push2(50);

System.out.println("Popped element from stack 1: " + twoStacks.pop1());


System.out.println("Popped element from stack 2: " + twoStacks.pop2());
}
}

You might also like