0

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!

Ho My Ha
  • 13
  • 5
  • whats wrong with the stack in the framework? https://msdn.microsoft.com/en-us/library/3278tedw%28v=vs.110%29.aspx – Jodrell Apr 02 '15 at 14:23

2 Answers2

0

Dynamic re-sizing means that you grow the stack once it's full.

growArray() could just double the current capacity, allocate a new array with the adjusted size and copy all the data from the old array into the new one.

wiseveri
  • 191
  • 1
  • 9
0

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
}
Dennis_E
  • 8,751
  • 23
  • 29
  • Instead of the for-loop you could write `Array.copy(data, newArray, Capacity);` – wiseveri Apr 02 '15 at 13:58
  • one more question. For the Size method to return the number of elements stored, how can I implement that? – Ho My Ha Apr 02 '15 at 14:08
  • @HoMyHa you have 'top'. That indicates the size. I would have named it 'size' anyway. (size is 1 greater than top, though) – Dennis_E Apr 02 '15 at 14:18