In: Computer Science
Please
Why do we need a dynamic stack? How to implement a dynamic array stack?(JAVA)
we know that stack uses LIFO princliple it stores value. we give size of the stack but if we have more data to store we want to increase the size for everything
for exampe: stack=new int[3];
in the above example the stack size is 3 but we have more than three datas then we want to double the stack then we have six size to fil datas but we want more than 6 then we again double the stack size thats why we are using dynamic stack.dynamic stack is like dynamic array we can change the length by using operations.
if we want to use more data than the stack size we can use the dynamic stack with the help of dynamic stack we can double the data size
we can implement dynamic array stack using creating a new function and within the function we can double the size by using length function.
for example
private void dousize(){
int temp[]=x;
x=new int[2*temp.length];
for(int i=0;i<=top;i++)
x[i]=temp[i];}
in the above example we create a function called dousize() we call the function in main.
we are creating an array name temp and assigning to x next line we double the size using length and using for loop.