In: Computer Science
Why do we need a dynamic stack and How to implement a dynamic array stack? ( Please answer in Java)
A stack stores elements in an ordered list and allows insertions and deletions at one end of the list in O(1) time. The dynamic stack array implements a stack using an array. The size of the array may be changed dynamically after insertions or deletions. For run-time requirements, the number of elements in the stack is n.
Example in Java:
public class DynamicArrayStack {
public static void main(String[] args) {
DynamicStack dstack=new DynamicStack(2);
System.out.println("--Pushing--");
dstack.push(1);
dstack.push(2);
dstack.display();
dstack.push(3);
dstack.push(2);
dstack.push(5);
dstack.display();
System.out.println("--Popping--");
dstack.pop();
dstack.pop();
dstack.pop();
dstack.display();
}
}
class DynamicStack {
private int top;
private int capacity;
private int[] array;
public DynamicStack(int cap) {
capacity = cap;
array = new int[capacity];
top = -1;
}
public void push(int data) {
if (isFull()){
expandArray(); //if array is full then increase its capacity
}
array[++top] = data; //insert the data
}
public void expandArray() {
int curr_size = top + 1;
int[] new_array = new int[curr_size * 2];
for(int i=0;i<curr_size;i++){
new_array[i] = array[i];
}
array = new_array; //refer to the new array
capacity = new_array.length;
}
public boolean isFull() {
if (capacity == top+1)
return true;
else
return false;
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty");
return -1;
} else {
reduceSize(); //function to check if size can be reduced
return array[top--];
}
}
public void reduceSize() {
int curr_length = top+1;
if (curr_length < capacity / 2) {
int[] new_array = new int[capacity / 2];
System.arraycopy(array, 0, new_array, 0, new_array.length);
array = new_array;
capacity = new_array.length;
}
}
public boolean isEmpty() {
if (top == -1)
return true;
else
return false;
}
public void display() {
for (int i = 0; i <= top; i++) {
System.out.print(array[i] + "=>");
}
System.out.println();
System.out.println("ARRAY SIZE:" + array.length);
}
}
-----------------------
The code above shows pushing and poping in java language in dynamiv array stack.
-----------------------------------------------------Please Upvote-------------------------------------------------------------