Question & Answer: I need help with a program in Java. Please provide a code for this in Java. Please make it simple and basic……

I need help with a program in Java. Please provide a code for this in Java. Please make it simple and basic.

A Century Stack is a stack with a fixed size of 100. If a Century Stack is full, then the element that has been on the stack, the longest, is removed to make room for the new element. Create a CenturyStackInterfacefile that capture this specification of a Century Stack.

Expert Answer

 

The element with the longest time will be the first element put in the stack.

import java.io.*;

class CenturyStack{

private int size;
private int array[];

public CenturyStack() {
array = new int[100];
size = 0;
}

public void push(int a){
if (size < 100){
array[size] = a;
size = size + 1;
}
else {
int temp[] = new int[size];
for (int i = 0; i<size; i++){
temp[i] = pop();
}
for (int i = 0; i<size-1; i++){
array[i] = temp[i];
}
size = size-1;
array[size] = a;
size = size + 1;

}
}
public int pop(){
if (size > 0){
size = size – 1;
return array[size];
}
else {
System.out.println(“Stack is empty”);
return -1;
}
}

}

public class DemoCenturyStack{
public static void main(String[] args){

CenturyStack ct = new CenturyStack();
for (int i = 0; i<100; i++)
ct.push(i);
ct.push(5);
System.out.println(ct.pop());
}
}

Still stressed from student homework?
Get quality assistance from academic writers!