Create a stack class in java where the stack is defined using an String type array and the size of the stack is provided by an instance variable. There should be an instance variable to track the top index of the stack. Define a constructor to initialize the size of the stack and the variable to track the top index of the stack. It is to be said that the minimum size of the stack should be 10. Define two methods void push(String item) and String pop() to conduct the insertion and deletion process in the stack. After filling up the stack with the maximum items possible, pop out 4 items from the stack and then output the sum of the remaining items in the stack.
public class Stack {
private String[] data;
private int top;
public int size;
public Stack(int size) {
this.size = Math.max(10, size);
data = new String[this.size];
top = -1;
}
public void push(String item) {
if (top < data.length) {
data[++top] = item;
}
}
public String pop() {
return data[top--];
}
}
Comments
Leave a comment