Click here to Skip to main content
13,091,417 members (69,396 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

2.5K views
1 bookmarked
Posted 12 Aug 2017

Custom Stack Using Array In C#

, 12 Aug 2017
Rate this:
Please Sign up or sign in to vote.
This tip demonstrates how to create a custom stack using array in C# by using recursion to manage items positions internally when pop and push methods are called. This is a simple programming practice for beginners.

Introduction

In this tip, I have demonstrated how to create a simple custom stack by using array in C#. This is helpful for beginners to understand array and recursion functions. Also, sometimes in interviews, these type of code practices are required to evaluate candidate basics.

Background

The basic idea behind this code practice is to create a custom array stack utility which needs to specify its capacity to store maximum items and provide two methods Pop & Push to add read items and add items into the array and manage items position when these methods get called.

Using the Code

The custom array stack is based on following logic which manages item push and pop functionality internally.

  • A CustomArray class which takes a parameter capacity to set maximum length of the stack in the constructor.
  • Pop method to get topmost item from the array and manage item positions.
  • Push method to add item to the zero index of the array and manage item positions.
  • suffleStackItemsOnPush method rearrange items recursively when push method is called.
  • suffleStackItemsOnPop method rearranges items recursively when pop method is called.
  • nextBlankIndex method to get next available index of the array.

Create custom array stack class with all functions.

public class CustomStack
{
    private int _capacity;
    private int _length;
    private int?[] _arrayStack;
    
    public CustomStack(int capacity)
    {
        this._capacity = capacity;
        this._length = capacity - 1;
        this._arrayStack = new int?[capacity];
    }
    
    public int? Pop()
    {
        int? value = null;
        if (this._arrayStack[0].HasValue)
        {
            // Get index 0 value
            value = this._arrayStack[0].Value;
            
            // Swap recursively 
            int nextIndex = this.nextBlankIndex();
            int lastIndex = nextIndex == 0 ? _length : nextIndex;
            this.suffleStackItemsOnPop(lastIndex, 0);
            this._arrayStack[lastIndex] = null;
            Console.WriteLine("Item Popped: {0}", value);
        }
        else
        {
            Console.WriteLine("Stack is empty.");
        }            
        return value;
    }
    
    public void Push(int item)
    {
        if (!this._arrayStack[_length].HasValue)
        {
            int nextIndex = this.nextBlankIndex();
            this.suffleStackItemsOnPush(nextIndex);
            this._arrayStack[0] = item;
            Console.WriteLine("Item pushed: {0}", item);
        }
        else
        {
            Console.WriteLine("Stack full.");
        }
    }
    
    private void suffleStackItemsOnPush(int nextIndex)
    {
        if (nextIndex > 0)
        {
            this._arrayStack[nextIndex] = this._arrayStack[nextIndex - 1];
            nextIndex = nextIndex - 1;
            
            // Shuffle items recursively
            suffleStackItemsOnPush(nextIndex);
        }
    }
    
    private void suffleStackItemsOnPop(int lastIndex, int nextIndex)
    {
        if (lastIndex > nextIndex)
        {
            this._arrayStack[nextIndex] = this._arrayStack[nextIndex + 1];
            nextIndex = nextIndex + 1;
            
            // Suffle items recursively
            suffleStackItemsOnPop(lastIndex, nextIndex);
        }
    }
    
    private int nextBlankIndex()
    {
        int index = 0;
        for (int i = 0; i < _capacity; i++)
        {
            if (!this._arrayStack[i].HasValue)
            {
                index = i;
                break;
            }
        }
        return index;
    }
}

Using custom array stack in main method.

static void Main(string[] args)
{
    int capacity = 10;
    CustomStack arrayStack = new CustomStack(capacity);

    // Items pushed into stack
    Console.WriteLine("--Pushed Items");
    for (int i = 1; i <= capacity; i++)
    {
        arrayStack.Push(i);
    }

    Console.WriteLine(Environment.NewLine);

    // Items popped from stack
    Console.WriteLine("--Poped Items");
    for (int i = 1; i <= capacity; i++)
    {
        var getValue = arrayStack.Pop();
    }

    Console.ReadLine();
}

That’s it! You can set any number of capacity and use this custom array stack. The higher capacity may lead to stack overflow so keep in mind to set a reasonable number as stack should not be used for a huge number of items in general.

Points of Interest

We can create and use our own custom stack without using C# in build stack. And I hope this will help you to think around array and recessions.

Thanks for reading!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

PSahu
Software Developer (Senior)
India India
A professional .net developer having 7+ years of expertise in software development. My technology expertise includes C#, WPF, WCF, Asp.Net MVC, Web Api, Sql Server, HTML5 & Angular2*.

You may also be interested in...

Pro

Comments and Discussions

 
GeneralMy vote of 1 Pin
The Power14-Aug-17 9:54
memberThe Power14-Aug-17 9:54 
SuggestionFIFO and LIFO Pin
InvisibleMedia13-Aug-17 1:59
memberInvisibleMedia13-Aug-17 1:59 
QuestionFew things to consider Pin
Wendelius12-Aug-17 22:23
mvpWendelius12-Aug-17 22:23 
AnswerRe: Few things to consider Pin
George Swan13-Aug-17 19:29
memberGeorge Swan13-Aug-17 19:29 
QuestionLacks a lot... Pin
Kornfeld Eliyahu Peter12-Aug-17 20:28
mvpKornfeld Eliyahu Peter12-Aug-17 20:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170813.1 | Last Updated 12 Aug 2017
Article Copyright 2017 by PSahu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid