Search code examples
c#arraysstackdynamic-resizing

Array-based Stack using c#


I already implemented method to implement Push, Pop, Peek on an array-based Stack. But i'm stuck at the method to return the size of the stack and implement dynamic resizing as I dont understand what is "dynamic resizing" is. Please help!


Solution

  • First, I'd like to mention some things that are wrong with your program.
    Do you really want to make the array public? You don't want callers to modify the array directly.
    In the constructor, you should make sure that capacity is not a negative number.
    Some of your properties can just be fields.
    Capacity is just the length of the array, it should be readonly.

    private int[] data;
    private int top;
    
    private int Capacity { get { return data.Length; } }
    

    The Push method doesn't make sense. If the array is full, you're just cancelling the push operation. That's when you need to grow the array.

    public void Push(int value) {
        if (IsFull()) GrowArray();
        ++top;
        this.data[top] = value;
    }
    
    private void GrowArray() {
        //determine what the new length should be
        int newLength = Capacity == 0 ? 4 : Capacity * 2;
        int[] newArray = new int[newLength];
        //copy all the items to the new array.
        for (int i = 0; i <= top ++i)
            newArray[i] = data[i];
        //instead of the for-loop you can write:
        //Array.Copy(data, newArray, Capacity);
        data = newArray; //replace the old array with the new
    }