How to efficiently implement k stacks in a single array?
Create a data structure kStacks that represents k stacks. Implementation of kStacks should use only one array, i.e., k stacks should use the same array for storing elements. Following functions must be supported by kStacks.
push(int x, int sn) –> pushes x to stack number ‘sn’ where sn is from 0 to k-1
pop(int sn) –> pops an element from stack number ‘sn’ where sn is from 0 to k-1
publicclassGFG {// A Java class to represent k stacks in a single array of size nstaticclassKStack {int arr[]; // Array of size n to store actual content to be stored in stacksint top[]; // Array of size k to store indexes of top elements of stacksint next[]; // next[i] will store the next free space if you want to occupy this space in// original array otherwise it something already is present at this index, then// it will store the index of element just below this in the stackint n, k;int free; // To store the first free space index// ConstructorKStack(int k1,int n1) {// Initialize n and k, and allocate memory for all arrays k = k1; n = n1; arr =newint[n]; top =newint[k]; next =newint[n];// Initialize all stacks as emptyfor (int i =0; i < k; i++) top[i] =-1;// Initialize all spaces as free free =0;for (int i =0; i < n -1; i++) next[i] = i +1; next[n -1] =-1; // Last index has no free space after it }// To push an item in stack number 'sn' where sn is from 0 to k-1voidpush(int item,int sn) {// If there is no free space availableif (free ==-1) {System.out.println("Stack Overflow");return; }int i = free; // Store index of first free slot// Update index of free slot to index of next slot in free list free = next[i];// Update next of top and then top for stack number 'sn' next[i] = top[sn]; top[sn] = i;// Put the item in array arr[i] = item; }// To pop an from stack number 'sn' where sn is from 0 to k-1intpop(int sn) {// If stack is emptyif (top[sn] ==-1) {System.out.println("Stack Underflow");returnInteger.MAX_VALUE; }// Find index of top item in stack number 'sn'int i = arr[top[sn]]; top[sn] = next[i]; // Change top to store next of previous top// Attach the previous top to the beginning of free list next[i] = free; free = i;// Return the previous top itemreturn arr[i]; } }}