DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Aniruddha has posted 40 posts at DZone. View Full User Profile

Implement 3 Stacks using single array - C#

06.01.2012
| 5676 views |
  • submit to reddit
/// <summary>
        /// 3 Stacks are Implemented in this class using 1 array
        /// </summary>
        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

            }

            /// <summary>
            /// Push item on stack
            /// </summary>
            /// <param name="stackNum">stack number (ie. 0/1/2)</param>
            /// <param name="data"></param>
            public void PushOnStack(int stackNum, int data)
            {
                _arr[_stacksAvailableSlots[stackNum]++] = data;
            }

            /// <summary>
            /// Pop item from stack
            /// </summary>
            /// <param name="stackNum">stack number (ie. 0/1/2)</param>
            public int PopStack(int stackNum)
            {
                return _arr[--_stacksAvailableSlots[stackNum]];
            }

            /// <summary>
            /// Gives count of items in a stack
            /// </summary>
            /// <param name="stackNum">stack number (ie. 0/1/2)</param>
            /// <returns></returns>
            public int StackCount(int stackNum)
            {
                return (_stacksAvailableSlots[stackNum] - (_stackSize * stackNum));
            }

            /// <summary>
            /// Printing contents of stack
            /// </summary>
            /// <param name="stackNum">stack number (ie. 0/1/2)</param>
            public void PrintStack(int stackNum)
            {
                for (int i = stackNum * _stackSize; i < _stacksAvailableSlots[stackNum]; i++)
                {
                    Console.WriteLine(_arr[i]);
                }
            }
        }
3 Stacks are Implemented in this class using 1 array.