Javatpoint Logo
Javatpoint Logo

How to Efficiently Implement kStacks in a Single Array?

This article discusses a general solution for k stacks. The entire research objectives is provided below. Make a data structure called kStacks to represent k stacks. Only one array should be used in the kStacks implementation, i.e., kstacks should store elements in the same array.

kStacks must support the following functionalities.

Method 1 (Divide the array into no/k slots)

A simple method for implementing kstacks is to divide the array into k slots of size no/k each and assign the slots to various stacks, i.e., use arr1[0] to arr1[no/k-1] for the first stack and arr1[no/k] to arr1[2no/k-1] for stack2, in which arr1[] is the array to be used to implement two stacks and array size is no. The problem with this method is that it makes inefficient use of array space. When there is space in arr1[], a stack push operation in stack overflow may occur. For example, suppose k is 2 and the array size (n) is 6, and we push three elements to the first stack but nothing to the second. Even if we have space in the array for three more elements, there will be overflow if we move the fourth member to the first.

Method No. 2 (A space efficient implementation)

To efficiently implement k stacks in an array, two extra arrays are used. It may not sound right for integer stacks, but stack elements, such as stacks of workers, learners, and so on, might be huge, with hundreds of bytes in each item. The extra space utilised is comparatively minimal because we use two integer arrays as extra storage space for such massive stacks.

The following are the two additional arrays:

1) top1[]: This is a k-dimensional array that preserves the top items' indexes in all stacks.

2) next1[]: This has a capacity of n and keeps the next item indexes for the elements in array arr1[].

Here, arr1[] is the real array containing k stacks. In addition to k stacks, a stack of free spaces in arr1[] is kept. The top of this stack is saved in a variable called 'free.' To signal that all stacks are empty, all entries in top1[] are initialised as -1. Because all slots are initially free and referring to the following slot, all entries next1[i] are initialised as i+1. The top of the free stack, 'free,' is set to 0.

The implementation of the aforesaid notion is shown below.

C++ Program:


The element removed from stack 2 is 45
The element removed from stack 1 is 39
The element removed from stack 0 is 7

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA