In: Computer Science
Stack2540Array
import java .io .*;
import java . util .*;
public class Stack2540Array {
int CAPACITY = 128;
int top ;
String [] stack ;
public Stack2540Array () {
stack = new String [ CAPACITY ];
top = -1;
}
1
public int size () { return top + 1; }
public boolean isEmpty () { return (top == -1); }
public String top () {
if ( top == -1)
return null ;
return stack [ top ];
}
public void push ( String element ) {
top ++;
stack [top ] = element ;
}
3.2 Dynamic Array
To save computer memory, we need to use dynamic array. In the rst
version of our stack implementation, the instance variable has
a
xed capacity, which is 128. There will be an error when the stack
is bigger than 128. For bigger data, you increased the array size.
But
that very long array could be wasted for smaller data.
in java please.
Solution:
Java Code:
import java .io .*;
import java . util .*;
public class Stack2540Array {
private ArrayList<String> stack ; // private member of type
ArrayList.
// constructor for the class.
public Stack2540Array () {
stack = new ArrayList<String>();
}
// size_of_stack() function returns size of the stack.
public int size_of_stack() {
return stack.size();
}
// isEmpty() function checks whether stack is empty or not.
public boolean isEmpty () {
return (stack.size() == 0);
}
// top() function returns the top element of the stack.
public String top () {
return stack.get(stack.size()-1);
}
// push() function adds element to the stack.
public void push( String element ) {
stack.add(element);
}
// Driver function of the program.
public static void main(String[] args){
Stack2540Array dynamicArray=new Stack2540Array(); // creates an
object of class Stack2540Array.
dynamicArray.push("Dog"); // inserts "Dog".
dynamicArray.push("Cat"); // inserts "Cat".
dynamicArray.push("Bull"); // inserts "Bull".
dynamicArray.push("Lion"); // inserts "Lion".
dynamicArray.push("Mouse"); // inserts "Mouse".
// function call to size_of_stack().
System.out.println("The size of stack:
"+dynamicArray.size_of_stack());
// function call to top().
System.out.println("The top of stack: "+dynamicArray.top());
// function call to isEmpty().
System.out.println("Is stack empty?
"+dynamicArray.isEmpty());
}
}
Code screenshot:
Output screenshot: