2- Write a Java main program that determines whether a stack is n-partite or not. A stack is n-partite, if its elements appear n times sequentially. (A" Bn Cn ... X") To test your solution, you must add some elements into the stack as follows: s.push(1); s.push(1); s.push(1); s.push(8); s.push(8); s.push(8); s.push(5); s.push(5); s.push(5); s.push(3); s.push(3); s.push(3); At the end of the program, the stack can be empty. Example 1: Example 2: top top s: 333555 888 11 1 s: 18 18 18 18 18 6 6 6 66 18 18 18 18 18 22222 Output: true Output: true Example 3: Example 4: top top s: 333333 s: 9966 17 17 17 20 20 44 Output: true Output: false
Can you use only stack with this realization.
You must use ONLY stack data structure. Don’t use other different data structures like string or normal (pure) array or queue or array list.
- Don’t write any other method in the Stack class. All methods must be written in the main
- Don’t print the stack.
- The maksimum stack size is 100.
public class stack{
private int top;
private Object[] elements;
stack(int capacity){
elements = new Object[capacity];
top = -1;
}
void push(Object data) {
if (isFull())
System.out.println("Stack overflow");
else{
top++;
elements[top] = data;
}
}
Object pop(){
if(isEmpty())
{
System.out.println("Stack is empty");
return null;
}
else
{
Object retData = elements[top];
top--;
return retData;
}
}
boolean isEmpty(){
return(top == -1);
}
boolean isFull(){
return (top + 1 == elements.length);
}
int size(){
return top + 1;
}
Step by step
Solved in 3 steps with 2 images