我已经实现了在基于数组的堆栈上实现 Push、Pop、Peek 的方法。但是我坚持返回堆栈大小并实现动态调整大小的方法,因为我不明白什么是“动态调整大小”。请帮忙!
2 回答
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
}
动态调整大小意味着一旦堆栈已满,您就可以增加堆栈。
growArray() 可以将当前容量翻倍,分配一个调整后大小的新数组,并将旧数组中的所有数据复制到新数组中。