Implement 3 Stacks using single array - C#
Join the DZone community and get the full member experience.
Join For Free3 Stacks are Implemented in this class using 1 array.
///
/// 3 Stacks are Implemented in this class using 1 array
///
public class StacksUsingSingleArray
{
private static int _arrSize = 99;
private int[] _arr = new int[_arrSize];
private int[] _stacksAvailableSlots = new int[3];
private int _stackSize = 0;
public StacksUsingSingleArray()
{
_stackSize = _arrSize / 3;
_stacksAvailableSlots[0] = 0 * _stackSize;
_stacksAvailableSlots[1] = 1 * _stackSize; //33
_stacksAvailableSlots[2] = 2 * _stackSize; //66
}
///
/// Push item on stack
///
/// stack number (ie. 0/1/2)
///
public void PushOnStack(int stackNum, int data)
{
_arr[_stacksAvailableSlots[stackNum]++] = data;
}
///
/// Pop item from stack
///
/// stack number (ie. 0/1/2)
public int PopStack(int stackNum)
{
return _arr[--_stacksAvailableSlots[stackNum]];
}
///
/// Gives count of items in a stack
///
/// stack number (ie. 0/1/2)
///
public int StackCount(int stackNum)
{
return (_stacksAvailableSlots[stackNum] - (_stackSize * stackNum));
}
///
/// Printing contents of stack
///
/// stack number (ie. 0/1/2)
public void PrintStack(int stackNum)
{
for (int i = stackNum * _stackSize; i < _stacksAvailableSlots[stackNum]; i++)
{
Console.WriteLine(_arr[i]);
}
}
}
Data structure
Opinions expressed by DZone contributors are their own.
Comments