In: Computer Science
Dynamic Array
To save computer memory, we need to use dynamic array. In the first
version of our stack implementation, the instance variable has a
fixed 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 order to solve this dilemma, we start with a small array, and
increase the capacity only when it is needed. You will modify the
push operation by resizing the array when it overflows. And you
also need to implement the resize(...) method. The details of the
code are in the slides. Submit your dynamic stack in the submission
site here. Your can use the doubling strategy in resizing.
import java.io.*;
import java.util.*;
public class Stack2540ArrayDynamic {
int CAPACITY = 128;
int top;
String[] stack;
public Stack2540ArrayDynamic() {
stack = new String[CAPACITY];
top = -1;
}
public int size() {
return top + 1; }
public boolean isEmpty() {
return (top == -1); }
public String top() {
if (top == -1)
return
null;
return stack[top];
}
// add resize method
// add pop method
public void push(String element) {
// add something here
top++;
stack[top] = element;
}
}
* Please complete the resize, pop, and push methods.
CODE:
import java.io.*;
import java.util.*;
public class Stack2540ArrayDynamic {
int CAPACITY = 10;//making capacity small first
int top=-1;
String[] stack;
public Stack2540ArrayDynamic() {
stack = new String[CAPACITY];
top = -1;
}
public int size() { return top + 1; }
public boolean isEmpty() { return (top == -1); }
public String top() {
if (top == -1)
return null;
return stack[top];
}
// add resize method
public void resize() {
CAPACITY*=2;//using doubling method
}
// add pop method
public String pop()
{
if(isEmpty()) //checking if empty stack
{
System.out.println("UNDERFLOW");
}
String t=stack[top--];//removing last element
return t;
}
public void push(String element) {
// add something here
if(top>=(CAPACITY-1))
{
resize();//If OVERFLOW call resize
}
top++;
stack[top] = element;
}
}
SCREENSHOT OF CODE:
I hope I solved your query. In case of doubt feel free to ask in the comment section.